如何在没有外部库的情况下在 C++(11) 中创建强类型定义? [英] How to create a strong typedef in C++(11) without an external library?

查看:36
本文介绍了如何在没有外部库的情况下在 C++(11) 中创建强类型定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我知道您可以使用以下别名为类型设置别名:
typedef int *intPtr
但是 C++ 编译器无法区分它们:

So, I know you can alias types with the following:
typedef int *intPtr
But the C++ compiler can't differentiate between them:

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

我知道 C++ 没有没有这些技巧(如何使用 C++11 风格的强类型定义创建新的原始类型?),但我发现上述技巧难以阅读和理解.
我发现的唯一可行的解​​决方案是使用 Boost 库,但我强烈不喜欢使用外部库.
那么,是否有任何易于理解的技巧来制作强类型定义?

I am aware that C++ does not have this without some trickery (How can I create a new primitive type using C++11 style strong typedefs?), but I found said trickery hard to read and understand.
The only plausible solution I have found is to use the Boost library, but I have a strong distaste in using external libraries.
So, is there any easily-understandable trick to make a strong typedef?

推荐答案

A typedefusing 声明 不会引入新类型.

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

To get a new type you need to define one:

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;
}

在上面的例子中,我们利用聚合初始化来允许以这种方式使用 structs.

In the above example we take advantage of aggregate initialization to allow for the use of the structs in this way.

这篇关于如何在没有外部库的情况下在 C++(11) 中创建强类型定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆