在c++中从int派生不同且不可比较的类型

Deriving different and incomparable types from int in C++

本文关键字:可比较 类型 中从 int 派生 c++      更新时间:2023-10-16

我知道我不能从int中推导,甚至没有必要,这只是我想到的一个(非)解决方案。

我有一对(foo,bar),它们都由一个int内部表示,但我希望typeof(foo)typeof(bar)不可比较。这主要是为了防止我将(foo,bar)传递给期望(bar, foo)的函数。如果我理解正确,typedef不会这样做,因为它只是一个别名。最简单的方法是什么?如果我要为foobar创建两个不同的类,那么显式地提供int支持的所有操作符将是乏味的。我想避免这个

作为自己编写的替代方案,您可以使用boost/strong_typedef.hpp头中提供的BOOST_STRONG_TYPEDEF宏。

// 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.

BOOST_STRONG_TYPEDEF(int, foo)
BOOST_STRONG_TYPEDEF(int, bar)
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
}

你是正确的,你不能这样做与typedef。但是,您可以将它们包装在struct-enum对中,或者将int封装在struct中。

template<int N>
struct StrongType {  // pseudo code
  int i;
  StrongType () {}
  StrongType (const int i_) : i(i_) {}
  operator int& () { return i; }
  StrongType& operator = (const int i_) {
    i = i_;
    return *this;
  }
  //...
};
typedef StrongType<1> foo;
typedef StrontType<2> bar;

解决方案c++ 0 x :

enum class foo {};
enum class bar {};