由于模板实例化导致的意外类型
Unexpected type due to template instantiation
我有以下(简化)代码:
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++标准吗?如果是这样,这是有意的吗?
没有类型更改:MySpecialType
是int
的类型别名(同义词)。对,这两个是同一种类型。
在您的示例中,mirror_id
是VarArray<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++中对T*类型执行std::move的意外行为
- 为什么static_cast基础类型的枚举类int8_t获得意外值?
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- 来自 decltype 的意外输出类型
- 标记为 [数据成员] 时的意外类型'USN'
- 为什么对小于 4 个字节的整数类型的位操作会发生意外行为?
- 未声明的标识符和类型"int"从 main 调用类时出现意外错误
- C 意外值类型的范围V3 partial_sum视图
- 依赖于参数的查找在来自另一个命名空间的别名类型上意外行为
- 组合 std::forward、std::move 和 voltile 时出现意外的返回类型
- 语法错误:意外的类型'P_HDR'
- 类型结果之间的意外差异
- 来自异常声明的派生对象类型是否意外
- find_if() 在 const 函数中返回意外的迭代器类型
- 包装非POD类型:无警告,尺寸意外
- 类型为char的C++枚举,被编译器忽略或出现意外行为
- 具有统一初始化的自动将扩展到意外类型
- pow()在使用类型转换时会产生意外结果
- 由于模板实例化导致的意外类型
- 编译 moc 文件 Qt 4.5.2 intrin.h 意外类型 "void" Visual Studio 2015