C++:重新定义不同类型的模板类

标签 c++ c++11 templates enums template-specialization

我有两个(多个)枚举:

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) 和可能有更多这样的枚举?

最佳答案

这不是一个很好的解决方案,但是......您可以为 Choiches1Choiches2 使用公共(public)基础 (int) 并定义非专用案例为

template <int>
struct choice_traits;

此时的问题是 Choiches1::a == Coiches2::cChoiches1::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; };

您必须避免 Choiches1Choiches2 值之间的冲突。

如果您知道 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/

相关文章:

c++ - 将多个内存块呈现为单个连续内存块的容器

c++ - 编译Template类时出现数百个错误(第一个Template类)

angular - 如何在 angular 7 项目中集成 html 模板

c++ - 构造一个可以使用基于范围迭代的对象

c++ - 通过构造函数初始化 unique_ptr

c++ - 从字符串文字中推导模板参数

c++ - 在模板方法中,有没有办法检查当前类型是 int-variant 还是 float-variant?

c++ - XMMATRIX 对 2D 转换是否有效,或者我应该制作自定义 3x3 矩阵套件?

c++ - ofstream 不会将不同的数据写入两个不同的文件

c++ - OpenGL 变换