And*_*ner 13 c++ types typedef
在C++ 11中,是否有一种干净的方法来禁用typedef之间的隐式转换,或者你是否需要做一些令人讨厌的事情,比如在类中包装int并定义和删除各种运算符?
typedef int Foo;
typedef int Bar;
Foo foo(1);
Bar bar(2);
bar = foo; // Implicit conversion!
Run Code Online (Sandbox Code Playgroud)
C++标准说:
7.1.3 typedef说明符
使用typedef说明符声明的名称将成为typedef-name.在其声明的范围内,typedef-name在语法上等同于关键字,并按照第8章中描述的方式命名与标识符关联的类型.因此, typedef-name是另一种类型的同义词.typedef-name不会像类声明(9.1)或枚举声明那样引入新类型
但是例如class或struct引入新类型.在下面的示例uniqueUnused中,实际上只是用于创建不同的类型Value<int, 1> != Value<int, 2>.所以也许这是你正在寻找的东西.请记住,无法保证编译器摆脱外部结构!这个代码唯一保证它与int的大小相同
template<typename T, int uniqueUnused>
struct Value
{
Value() : _val({}) {}
Value(T val) : _val(val) { }
T _val;
operator T&() { return _val; }
// evaluate if you with or without refs for assignments
operator T() { return _val; }
};
using Foo = Value<int, 1>;
using Bar = Value<int, 2>;
static_assert(sizeof(Foo) == sizeof(int), "int must be of same size");
static_assert(sizeof(Bar) == sizeof(int), "int must be of same size");
Run Code Online (Sandbox Code Playgroud)
如果要基于类创建新类型,可以使用此示例(这不适用于标量类型,因为您无法从int继承):
class Foo : public Bar // introduces a new type called Foo
{
using Bar::Bar;
};
Run Code Online (Sandbox Code Playgroud)
HelloWorld解释了为什么你所拥有的不起作用.你需要通常所谓的"强者" typedef才能做你想做的事.一个示例实现是BOOST_STRONG_TYPEDEF:
#include <boost/serialization/strong_typedef.hpp>
BOOST_STRONG_TYPEDEF(int, a)
void f(int x); // (1) function to handle simple integers
void f(a x); // (2) special function to handle integers of type a
int main(){
int x = 1;
a y;
y = x; // other operations permitted as a is converted as necessary
f(x); // chooses (1)
f(y); // chooses (2)
}
Run Code Online (Sandbox Code Playgroud)
如果我们完成了typedef int a;,那么代码就会模糊不清.