我有两个(多个)枚举:
enum Choices1 : int
{
a,
b
};
enum Choices2 : int
{
c,
d
};
我希望能够将一个类型与这些枚举选择中的每一个相关联。如果我只有一组枚举 Choices1
,我可以介绍:
template <Choices1 c>
struct choice_traits;
然后针对每个条目专门化它:
template <>
struct choice_traits<Choices1::a>
{
using MyType = float;
};
template <>
struct choice_traits<Choices1::b>
{
using MyType = double;
但我希望能够对多个枚举执行此操作,同时使用相同的关键字,例如:
template <>
struct choice_traits<Choices1::a>
{...};
template <>
struct choice_traits<Choices1::b>
{...};
template <>
struct choice_traits<Choices2::c>
{...};
template <>
struct choice_traits<Choices2::d>
{...};
这可能吗?如果是这样,非特例是什么?
如果没有,是否有任何替代方法将类型关联到每个 (Choice1::a,Choice1::b,Choice2::c,Choice2::d)
和可能有更多这样的枚举?
最佳答案
这不是一个很好的解决方案,但是......您可以为 Choiches1
和 Choiches2
使用公共(public)基础 (int
) 并定义非专用案例为
template <int>
struct choice_traits;
此时的问题是 Choiches1::a == Coiches2::c
和 Choiches1::b == Choiches2::d
所以,如果你想定义类似的东西
template <>
struct choice_traits<Choices1::a>
{ using MyType = float; };
template <>
struct choice_traits<Choices1::b>
{ using MyType = double; };
template <>
struct choice_traits<Choices2::c>
{ using MyType = int; };
template <>
struct choice_traits<Choices2::d>
{ using MyType = long; };
您必须避免 Choiches1
和 Choiches2
值之间的冲突。
如果您知道 Choiches1
值的数量,您可以使用更大的数字开始 Choiches2
;例如,如果您确定 Choiches1
值少于 100,则可以按如下方式定义枚举
enum Choices1 : int
{ a = 0, b };
enum Choices2 : int
{ c = 100, d };
另一种解决方案可以为两个枚举使用偶数和奇数;像
enum Choices1 : int
{ a = 0, b = a+2 }; // add 2 for every next value
enum Choices2 : int
{ c = 1, d = c+2 }; // add 2 for every next value
下面是一个完整的例子
enum Choices1 : int
{ a = 0, b };
enum Choices2 : int
{ c = 100, d };
template <int>
struct choice_traits;
template <>
struct choice_traits<Choices1::a>
{ using MyType = float; };
template <>
struct choice_traits<Choices1::b>
{ using MyType = double; };
template <>
struct choice_traits<Choices2::c>
{ using MyType = int; };
template <>
struct choice_traits<Choices2::d>
{ using MyType = long; };
int main()
{
choice_traits<a>::MyType fl { 1.1f };
choice_traits<b>::MyType db { 2.2 };
choice_traits<c>::MyType in { 3 };
choice_traits<d>::MyType ln { 4L };
}
关于C++:重新定义不同类型的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42878565/