Reputation: 8528
I am using std::map<const char*, boost::any>
to store my library's settings. Each setting only uses a single underlying value type and I want to enforce this during configuration calls to set()
or similar. Settings are initialized with default values of the correct type.
Here is some pseudo code that hopefully shows what I'm trying to achieve:
using namespace std;
using namespace boost;
void set(map<const char *, any> &settings, const char *key, any &value)
{
if (type_of(value) != type_of(settings[key]) throw wrong_type_exception();
settings[key] = value;
}
Is it possible to trap type errors like this at runtime? I'd prefer not to have template functions in my API if possible.
I've used boost::any
but might consider boost::variant's which()
if that's the only viable solution.
Upvotes: 1
Views: 263
Reputation: 279335
value.type() != settings[key].type()
If settings[key]
doesn't previously exist, then settings[key].type()
is typeid(void)
, which compares equal to value.type()
if and only if value
is empty. So you won't be able to add new setting/value pairs via this function, but based on the pseudo-code that seems to be intended.
Upvotes: 2