I try to use a std::variant with an enum as part of the possible types. I have a compile error and i don't find the reason. If I use any other type instead of the enum, the code works. Here a part of my code:
#include <variant>
#include <iostream>
enum myEnum
{
INT8,
INT32
};
using value_t = std::variant<unsigned char , int, myEnum>;
template<class T, typename U = void>
struct visitHelper;
template<class T>
struct visitHelper <T>
{
T &v;
visitHelper(T &v): v(v){}
void operator()(const T v){ this->v = v; }
};
template <typename T> visitHelper(T &v) -> visitHelper<T>;
template<class T>
void updateValue(T &v, value_t value)
{
std::visit(visitHelper(v), value);
}
int main()
{
/* uncomment this block will cause an compiler error
myEnum e;
updateValue(e, INT32);
std::cout << e << std::endl;
*/
int i;
updateValue(i, 17);
std::cout << i << std::endl;
}
Why this code doesn't compile if I uncomment the block?
* First edit *
I modified the code to look like this and now it's working.
#include <variant>
#include <iostream>
enum myEnum
{
INT8,
INT32
};
using value_t = std::variant<unsigned char , int, myEnum>;
template<class T, typename U = void>
struct visitHelper;
template<class T>
struct visitHelper <T, std::enable_if_t< std::is_arithmetic_v< T > > >
{
T &v;
visitHelper(T &v): v(v){}
void operator()(const T v){ this->v = v; }
};
template<class T>
struct visitHelper <T, std::enable_if_t< std::is_enum_v< T > > >
{
T &v;
visitHelper(T &v): v(v){}
void operator()(const T v){ this->v = v; }
void operator()(const int v){ this->v = static_cast<T>(v); }
void operator()(...){ }
};
template <typename T> visitHelper(T &v) -> visitHelper<T>;
template<class T>
void updateValue(T &v, value_t value)
{
std::visit(visitHelper(v), value);
}
int main()
{
myEnum e;
updateValue(e, INT32);
std::cout << e << std::endl;
int i;
updateValue(i, 18);
std::cout << i << std::endl;
}