I have a fairly simple variant class which supports a predefined set of types, and provides an enumerate to indicate which of the available types is currently active. Something like this:
class variant
{
enum class type { integer, real, string, etc };
type active_type() const;
/* ... */
};
I would like to make the class into a template where the supported types are supplied as template parameters:
template <typename... T>
class variant
{
const std::type_info& active_type() const; // logical, but can't switch on it
/* ... */
};
A key feature that I rely on for catching errors is that I can switch
on the active type and the compiler will warn if any of the possible cases have been missed. This is not possible using the above design (nor using boost::variant
).
My question is, is there any way for me to automatically generate an enum with the same number of enumerates as the number of arguments in the parameter pack?
The actual names/values of the enumerates would not matter, as they can be hidden behind constexpr functions used to map the type to the correct enumerate. I could imagine an eventual usage like this:
template <typename... T>
class variant
{
enum class type { T... }; // magic here
// specializations provided to map T into type (for use in case labels)
template <typename T>
static constexpr type type_enum();
type active_type() const;
/* ... */
};
typedef variant<int, float, std::string> myvar;
myvar var;
switch (var.active_type())
{
case myvar::type_enum<int>(): // static constexpr function
...
break;
case myvar::type_enum<float>():
...
break;
} // warning: enumeration for string not handled in switch