One template specialization for several enum values

为君一笑 提交于 2021-02-07 13:17:26

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/53523928/one-template-specialization-for-several-enum-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!