This shows ways to convert between types using conversion templates.
Note: Automated conversion here is "best effort" and never throws an exception
- Conversion to Custom Types
Conversion is extendable for custom types by specializing the Convert template class (in evo
namespace). This is used to:
- Convert string to a value and return it – used by methods like convert() and split().
- Format string with value (reversed conversion) – used by methods like convert_set().
- Format value and append to string (reversed conversion) – used by methods like convert_add() and join().
Note: Include evo/type.h for conversion features
Example for converting String to bool – this is just an example and is already implemented:
template<> struct Convert<String,bool> {
static void set(String& dest,
bool value) {
if (value)
dest.set("true", 4);
else
dest.set("false", 5);
}
static void add(String& dest,
bool value) {
if (value)
dest.add("true", 4);
else
dest.add("false", 5);
}
static bool value(
const String& src) {
return src.getbool<bool>();
}
};
}
Some conversions make sense one way but not the other. Here's an example for converting char*
to String – again just an example and is already implemented:
template<> struct Convert<String,char*> {
static void set(String& dest, const char* value) {
dest.set(value);
}
static void add(String& dest, const char* value) {
dest.add(value);
}
};
}
See also: Common Stream/String Interface