开发者

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. Ho开发者_JS百科w 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.


You'll need to parameterize on another thing (e.g. an integer?). For example, define X as template <typename T, int N> struct X {...}; and use 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:

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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜