在c++中从int派生不同且不可比较的类型
Deriving different and incomparable types from int in C++
我知道我不能从int中推导,甚至没有必要,这只是我想到的一个(非)解决方案。
我有一对(foo,bar)
,它们都由一个int
内部表示,但我希望typeof(foo)
与typeof(bar)
不可比较。这主要是为了防止我将(foo,bar)
传递给期望(bar, foo)
的函数。如果我理解正确,typedef
不会这样做,因为它只是一个别名。最简单的方法是什么?如果我要为foo
和bar
创建两个不同的类,那么显式地提供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 {};
相关文章:
- 如果可推导类型上有替换,可变参数模板类型推导会使编译器崩溃
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 可变参数宏:无法通过"..."传递非平凡可复制类型的对象
- 我可以隐式地创建一个琐碎的可复制类型吗
- 是std::memcpy在不同的可复制类型之间的未定义行为
- 对于可移动类型,按值传递比重载函数更好吗?
- 包含可变参数包的第一个可转换类型的别名的结构
- 具有抑制移动构造/赋值的类型如何仍被视为可移动类型?
- 错误:无法通过'...'传递非平凡可复制类型的对象'class boost::filesystem::path'
- 使用临时存储区复制普通的可复制类型:允许吗
- 在可移动类型的构造函数 lambda 中捕获此内容的安全使用
- 在C++中,您能否像比较类型一样比较模板
- 在成员容器中复制具有仅可移动但可克隆类型的构造函数
- 可比较的类和二叉搜索树
- 非平凡可复制类型的值表示
- 可识别类型转换的数字文字
- 使用具有自定义比较类型的关联容器时出现的问题
- 可视类型转换自定义 C++ 类
- C++中的可扩展类型特征
- 交换包含非一般可复制类型的“std::aligned_storage”实例-未定义的行为