Same declaration two different types

拟墨画扇 提交于 2019-12-25 03:46:09

问题


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. How can I do it?


回答1:


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.




回答2:


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.




回答3:


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;



回答4:


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.



来源:https://stackoverflow.com/questions/4275369/same-declaration-two-different-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!