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

Unexpected type due to template instantiation

本文关键字:意外 类型 于模板 实例化      更新时间:2023-10-16

我有以下(简化)代码:

   template<typename T>
    class VarArray
    {
       typedef T* iterator;
    };
    void get_setpoints()
    {
         VarArray<int>::iterator mirror_id;
         int id;
         *mirror_id = id;
    }

*mirror_id的类型为int。到目前为止一切顺利。

现在我要在中间添加两个完全不相关的类型:

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

由于这些额外的类型,*mirror_id的类型突然变成了MySpecialType,而我真的希望它是int的类型。至少在Microsoft Visual Studio c++编译器和EDG c++编译器中是这样的。

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

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

没有类型更改:MySpecialTypeint的类型别名(同义词)。对,这两个是同一种类型。

在您的示例中,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; }
};