【发布时间】:2017-07-04 16:19:15
【问题描述】:
我有一个编译器错误的问题,看看这段代码:
template<class T>
struct MyStruct
{
};
template<>
struct MyStruct<int>
{
typedef int* type;
};
template<class T>
void foo(const typename MyStruct<T>::type myType)
{
}
int main()
{
const int* ptr = NULL;
foo<int>(ptr);
return 0;
}
问题是编译器忽略了 foo 函数上的 'const',使得对 foo 的调用非法(const int* 到 int*)。
严重性代码描述项目文件行抑制状态 错误 C2664 'void foo(const MyStruct::type)':无法将参数 1 从 'const int *' 转换为 'const MyStruct::type'
我在 Visual Studio 和 gcc 的 5.3 编译器中测试了以下代码,它们都出现了相同的错误。
编译器是否故意这样做?为什么会这样?
【问题讨论】:
-
const int* ptr不是 const 指针,它是指向 const 的指针。
标签: c++ visual-studio templates gcc