Evo C++ Library v0.5.1
Custom String Conversion and Formatting

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:

Note: Include evo/type.h for conversion features

Example for converting String to bool – this is just an example and is already implemented:

#include <evo/type.h>
namespace evo {
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:

#include <evo/type.h>
namespace evo {
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);
}
// Unsafe: Converting String to char* -- not defined so trying this conversion will give a compiler error
//template<class U> static char* value(U&)
};
}

See also: Common Stream/String Interface