在C++中从int派生不同的和无法比较的类型

san*_*san 18 c++ typechecking

我知道我无法从一个int派生而且甚至没有必要,这只是我想到的下面问题的一个(非)解决方案.

我有一对(foo,bar)都由内部代表,int但我希望它typeof(foo)是无与伦比的typeof(bar).这主要是为了防止我传递(foo,bar)给期望的函数(bar, foo).如果我理解正确,typedef不会这样做,因为它只是一个别名.最简单的方法是什么?如果我要创建两个不同的类foo,bar那么显式提供所有支持的运算符将是繁琐的int.我想避免这种情况.

Cat*_*lus 18

作为自己编写的替代方法,您可以使用标头中的BOOST_STRONG_TYPEDEFboost/strong_typedef.hpp.

// macro used to implement a strong typedef.  strong typedef
// guarentees that two types are distinguised even though the
// share the same underlying implementation.  typedef does not create
// a new type.  BOOST_STRONG_TYPEDEF(T, D) creates a new type named D
// that operates as a type T.
Run Code Online (Sandbox Code Playgroud)

所以,例如

BOOST_STRONG_TYPEDEF(int, foo)
BOOST_STRONG_TYPEDEF(int, bar)
Run Code Online (Sandbox Code Playgroud)


Arm*_*yan 10

template <class Tag>
class Int
{
   int i;
   public:
   Int(int i):i(i){}                //implicit conversion from int
   int value() const {return i;}
   operator int() const {return i;} //implicit convertion to int
};

class foo_tag{};
class bar_tag{};

typedef Int<foo_tag> Foo;
typedef Int<bar_tag> Bar;

void f(Foo x, Bar y) {...}
int main()
{
   Foo x = 4;
   Bar y = 10;
   f(x, y); // OK
   f(y, x); // Error
}
Run Code Online (Sandbox Code Playgroud)

  • 或者使用`BOOST_STRONG_TYPEDEF`([`boost/strong_typedef.hpp`](http://www.boost.org/doc/libs/release/boost/strong_typedef.hpp)). (6认同)
  • @Armen:你可以写`typedef Int <0> Foo;而不是那样.typedef Int <1> Bar;`如果类模板参数不是*type*,而是*整数值*.例如`template <int> class Int {};`如果你遵循这种方法,你不需要`xyz_tag`定义. (3认同)