gpt4 book ai didi

c++ - 由于模板实例化导致的意外类型

转载 作者:行者123 更新时间:2023-11-28 06:02:09 24 4
gpt4 key购买 nike

我有以下(简化的)代码:

   template<typename T>
class VarArray
{
typedef T* iterator;
};

void get_setpoints()
{
VarArray<int>::iterator mirror_id;
int id;
*mirror_id = id;
}

*mirror_id的类型是int。到目前为止,一切都很好。

现在我要在中间添加 2 个完全不相关的 typedef:

template<typename T>
class VarArray
{
typedef T* iterator;
};

typedef int MySpecialType;
typedef VarArray<MySpecialType> bool_t;

void get_setpoints()
{
VarArray<int>::iterator mirror_id;
int id;
*mirror_id = id;
}

因为这些额外的 typedef,*mirror_id 的类型突然变成了 MySpecialType,而我真的希望它是 int。这似乎至少适用于 Microsoft Visual Studio C++ 编译器和 EDG C++ 编译器。

我认为这很可怕的原因是一些嵌套的未知包含文件可能会突然将您的变量类型更改为其他类型。你不知道它,即使你知道也很难弄清楚它从何而来。

所以我的问题是,这种行为是否符合 C++ 标准?如果是这样,是故意的吗?

最佳答案

没有类型变化:MySpecialTypeint 的类型别名 (synonim) .没错:这两个是同一类型。

在您的示例中,mirror_idVarArray<int>::iterator , 还有 MySpecialType*还有int* .这些都是相同的类型。

让您感到困惑的是 MSVC++ 没有调用与您在程序中同名的变量类型(这是 MSVC++ 的一个错误,应该修复)。

据我所知(从评论中)你期望所谓的“强类型定义”,C++ 不直接支持它 - 你可以把你的 int在一个结构中,然后转发所有必要的操作。

class MySpecialType
{
int wrapped_int;
public:
MySpecialType(int a) : wrapped_int(a) { }
explicit operator int() const { return wrapped_int; }
int get() const { return wrapped_int; }
};

关于c++ - 由于模板实例化导致的意外类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33057722/

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