我知道我无法从一个int派生而且甚至没有必要,这只是我想到的下面问题的一个(非)解决方案.
我有一对(foo,bar)都由内部代表,int但我希望它typeof(foo)是无与伦比的typeof(bar).这主要是为了防止我传递(foo,bar)给期望的函数(bar, foo).如果我理解正确,typedef不会这样做,因为它只是一个别名.最简单的方法是什么?如果我要创建两个不同的类foo,bar那么显式提供所有支持的运算符将是繁琐的int.我想避免这种情况.
Cat*_*lus 18
作为自己编写的替代方法,您可以使用标头中的BOOST_STRONG_TYPEDEF宏boost/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)