一种模板专用化,可用于多个枚举值 [英] One template specialization for several enum values
问题描述
通常,如果我想通过枚举创建一个模板化(数据)类,我会写这样的东西
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;
};
然后,如果我想对 Modes :: m1
使用与 Modes :: m2
相同的专业化,我会再次写同样的专业化.有没有一种方法可以为多个枚举值编写一个专门化的文字?我已经在SFINAE上尝试过了,但是我没有成功.
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;
};
这不能编译.特别是在我想对 Modes :: m3
进行不同的专业化之后.我已经尝试过在SO上找到许多类似的解决方案,但似乎没有任何解决方案.
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.
推荐答案
您应将 enable_if
放在显式的 DataHolder
专业名称中,该专业名称与默认名称相匹配.如果 enable_if
中的条件评估为 true
,则将选择专业化.
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; */
}
这篇关于一种模板专用化,可用于多个枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!