繁体   English   中英

同一声明有两种不同类型

[英]Same declaration two different types

我希望能够做到这一点:

X<int> type_0;
X<int> type_1; 

我希望type_0和type_1是两种不同的类型。 我该怎么做?

template < typename T, int I > class X; 

X<int, __LINE__ > x0; 
X<int, __LINE__ > x1;

x0和x1将是不同的类型,如果它们不在文件的同一行,则其他类似的声明也将是不同的类型。

您可以使用顺序标签:

template <typename T, int Tag> class X { ... };

typedef X<int, 0> type_0;
typedef X<int, 1> type_1;

另外,您可以使用继承:

class type_0 : X<int> { ... };
class type_1 : X<int> { ... };

但这遇到了一些困难,例如需要转发构造函数参数以及混合分配语义和继承的危害。

您需要在另一件事上进行参数化(例如,整数?)。 例如,将X定义为template <typename T, int N> struct X {...}; 并使用X<int,0> type_0; X<int,1> type_1 X<int,0> type_0; X<int,1> type_1 如果模板参数匹配,则它们是同一类型。

创建一个从X模板类继承的类,如下所示:

template <int I>
class type_i : public X<int>
   {
   };

typedef type_i<0> type_0;
typedef type_i<1> type_1;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM