简体   繁体   English

同一声明有两种不同类型

[英]Same declaration two different types

I would like to be able to do this: 我希望能够做到这一点:

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

and I would like for type_0 and type_1 to be two different types. 我希望type_0和type_1是两种不同的类型。 How can I do it? 我该怎么做?

template < typename T, int I > class X; 

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

x0 and x1 will be different types as will any other declarations like this if they are not on the same line in the file. x0和x1将是不同的类型,如果它们不在文件的同一行,则其他类似的声明也将是不同的类型。

You could use ordinal tags: 您可以使用顺序标签:

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

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

Alternatively, you could use inheritance: 另外,您可以使用继承:

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

But this suffers from some difficulties, such as the need to forward constructor parameters and hazards with mixing assignment semantics and inheritance. 但这遇到了一些困难,例如需要转发构造函数参数以及混合分配语义和继承的危害。

You'll need to parameterize on another thing (eg an integer?). 您需要在另一件事上进行参数化(例如,整数?)。 For example, define X as template <typename T, int N> struct X {...}; 例如,将X定义为template <typename T, int N> struct X {...}; and use X<int,0> type_0; X<int,1> type_1 并使用X<int,0> type_0; X<int,1> type_1 X<int,0> type_0; X<int,1> type_1 . X<int,0> type_0; X<int,1> type_1 If template parameters match, they are the same type. 如果模板参数匹配,则它们是同一类型。

Make a class that inherits from the X template class, like this: 创建一个从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