gpt4 book ai didi

c++ - 如何在没有外部库的情况下在 C++(11) 中创建强类型定义?

转载 作者:行者123 更新时间:2023-11-28 00:04:25 24 4
gpt4 key购买 nike

所以,我知道你可以使用以下类型别名:
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?

最佳答案

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允许以这种方式使用结构

关于c++ - 如何在没有外部库的情况下在 C++(11) 中创建强类型定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36538818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com