如何在没有外部库的情况下在C ++(11)中创建强大的typedef?

时间:2016-04-11 02:18:45

标签: c++ typedef

所以,我知道您可以使用以下内容对别名进行别名:
typedef int *intPtr
但是C ++编译器无法区分它们:

typedef int foo  
typedef int bar  
foo x = 5;  
bar y = 7;  
int z = x + y;  // checks out  

我知道C ++ 没有没有一些诡计(How can I create a new primitive type using C++11 style strong typedefs?),但我发现这个诡计难以阅读和理解。
我找到的唯一合理的解决方案是使用Boost库,但我在使用外部库时有一种强烈的厌恶。
那么,是否有任何易于理解的技巧来制作强大的typedef?

1 个答案:

答案 0 :(得分:2)

typedefusing声明will not introduce a new type

要获得新类型,您需要定义一个:

struct foo { int x; };
struct bar { int x; };

int main()
{
    //typedef int foo;
    //typedef int bar;
    foo x{5};
    bar y{7};
    int z = x + y;  // now doesn't compile, wants an operator+() defined  
    return 0;
}

在上面的示例中,我们利用aggregate initialization允许以这种方式使用structs