Reads and writes values in memory using stored type - base types (char, int, double...) or std::string. Caster uses a pointer provided by the user. The pointer points to a memory segment that stores base type objects (char, int, ...). The type may change dynamically.
The implementation is based on function pointers to predefined template functions performing casts between base types.
As such, does not support arrays. See derived classes:
#include <iostream>
#include "drain/Caster.h"
using namespace std;
template <class T>
ostr << " " << drain::Type::getTypeChar(typeid(T)) << " = '";
ostr.precision(15);
ostr << c.
get<T>() <<
"'";
ostr << endl;
}
void retrieveAllTypes(
const drain::Caster & c, std::ostream & ostr = std::cout){
ostr << "Caster value = '";
ostr <<
"' [" << drain::Type::getTypeChar(c.
getType()) <<
']';
ostr << ", retrieved (casted) output values:\n";
retrieve<int>(c);
retrieve<unsigned short>(c);
retrieve<char>(c);
retrieve<unsigned char>(c);
retrieve<bool>(c);
retrieve<float>(c);
retrieve<double>(c);
retrieve<std::string>(c);
std::cout << '\n';
}
template <class T>
void traverseAll(const T & value){
std::cout << "Source value = '" << value << "', type = [" << drain::Type::getTypeChar(typeid(T)) << "]\n";
char buffer[sizeof(double)];
static const size_t TYPE_COUNT(8);
static const std::type_info *types[TYPE_COUNT] = {
&typeid(int),
&typeid(unsigned short),
&typeid(char),
&typeid(unsigned char),
&typeid(bool),
&typeid(float),
&typeid(double),
&typeid(void),
};
for (size_t i = 0; i < TYPE_COUNT; ++i) {
const std::type_info & t = *types[i];
try {
} catch (const exception & e) {
std::cerr << e.what() << std::endl;
std::cerr << " => Caster::put() failed" << std::endl;
}
retrieveAllTypes(caster);
}
std::string s;
caster.link(s);
retrieveAllTypes(caster);
std::cout << "# Caster: " << std::endl;
double d = 0.1234;
c2.link(d);
caster.link(c2);
retrieveAllTypes(caster);
cout << '\n';
}
int main(int argc, char **argv){
if (argc==1){
std::cout << "Usage: " << argv[0] << "<value> [<value2> <value3> ...]\n";
std::cout << "Example:\n " << argv[0] << " 0 67 123.456 true 'Hello, world!' \n";
std::cout << "Native examples:\n\n";
traverseAll(12345);
traverseAll('a');
traverseAll(true);
traverseAll(-0.2191);
traverseAll("Hello, world!");
return 0;
}
else {
for (int i = 1; i < argc; ++i) {
traverseAll(argv[i]);
}
}
return 0;
}
const std::type_info & getType() const
Returns type_info of the current type.
Definition: Caster.h:144
T get(const void *p) const
Default implementation throws an error. See specialized implementation below.
Definition: Caster.h:194
void setType(const std::type_info &t)
Calls setType<T>() for which typeid(T) = t.
Definition: Caster.h:119
std::ostream & toOStream(std::ostream &ostr, const void *p) const
Write data to output stream.
Definition: Caster.h:236
void put(void *p, const T &x) const
Default conversion (for unconventional types). Uses std::stringstream for conversion.
Definition: Caster.h:157