Normally if I want to have a templated (data) class by enum I would write something like this
enum class Modes : int
{
m1 = 1,
m2 = 2,
m3 = 3
};
template <Modes M>
class DataHolder
{
};
template<>
class DataHolder<Modes::m1>
{
public: int a = 4;
};
Then if I want the same specialization for the Modes::m1
as for the Modes::m2
I would write the same specialization again. Is there a way to write one specialization for several enum values? I have tried it with SFINAE, but I am not succesfull.
template <Modes M, typename = void>
class DataHolder
{
};
template<Modes M, typename = typename std::enable_if<M == Modes::m1 || M == Modes::m2>::type>
class DataHolder
{
public: int a = 4;
};
This doesn't not compile. Especially, after I would like to carry on with different specialization for Modes::m3
. I've tried many similiar solution found here on SO, but nothing seems to be solving the issue.
You should put the enable_if
in an explicit specialization of DataHolder
which matches the default one. The specialization will be chosen if the condition in the enable_if
evaluates to true
.
template <Modes M, typename = void>
class DataHolder
{
};
template<Modes M>
class DataHolder<M, typename std::enable_if<M == Modes::m1 || M == Modes::m2>::type>
{
public: int a = 4;
};
int main()
{
DataHolder<Modes::m1> a; a.a;
DataHolder<Modes::m3> b; /* b.a; */
}
live example on godbolt.org
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With