I'm a little new to C++ meta-programming/SFINAE, and I'm having trouble with developing a check to see if a type passed in to a method is contained within a predefined type-list. The context here is that I'd like to check against if the type that's being registered in my variant matches the output type in another structure. Each item that's registered in my application is mapped to another item (in a structure) via a tag (some number). I'd like to create a type-map that can be used at compile time to raise an assertion if the type that is to be registered doesn't match the type of the item in my wire protocol structure.
So something like:
// register elements in type map:
type_map::register(ID_1, decltype(wire_type_item_1));
type_map::register(ID_2, decltype(wire_type_item_2));
... etc.
// and when types are registered
template<typename T>
void add_item(const uint32_t id, const T item)
{
// add static_assert here
// look up type based on ID, and compare to type passed in
// when add_item is called
static_assert(std::is_same<type_map::find(id), decltype(T),
"Attempted to register type that does not match wire type");
...
}
I'd appreciate any pointers on where to start/how to go about doing this - thanks!
Here's one approach for creating a compile-time map between classes.
In your code sample, though, you have the following line:
static_assert(std::is_same<type_map::find(id), decltype(T), "Attempted to register type that does not match wire type");The issue with this is thatidis a runtime variable. You can't usestatic_assertat run-time.If you do want to lookup types in this map at runtime, it's a bit more complicated. I would suggest using a metaprogramming library like
hana, as it allows you to do things like loop through all elements of a compile-time data structure at run time.