在 Visual C++ 下使用模板专用化时编译器错误
Compiler error when using template specialization under Visual C++
我有以下 cpp 代码:
#include <iostream>
#include <limits>
// C2589 when compiling with specialization, fine when compiling without
template<typename T>
void foo(T value = std::numeric_limits<T>::infinity() )
{
}
// this specialization causes compiler error C2589 above
template<>
void foo<float>( float value )
{
}
int main()
{
foo<float>();
return 0;
}
当我尝试使用Visual Studio 2013编译它时,我收到以下错误:
..check2main.cpp(5) : error C2589: '::' : illegal token on right side of '::'
..check2main.cpp(5) : error C2059: syntax error : '::'
如果我不包括专业化foo<float>
,该程序编译得很好。代码也可以很好地编译,包括 gcc 4.8.4 下的专用化,这表明 Visual C++ 编译器存在一些问题。
代码是否正确,是否应该编译?是否有针对视觉C++的解决方法?
通过在调用foo<float>();
时省略参数,您将编译器置于难题中。编译器同时得出结论,专用函数是正确的选择,因为你明确地说<float>
,而不是那个,因为没有参数。然后编译器到达通用版本,但它不能,因为有一个专门的版本。即使是HAL9000也无法弄清楚那个,除非它是用 gcc 构建的。VC++ 错误地处理这种情况。可能是一个错误,而不是"设计使然"。
Visual C++的解决方法是使用重载:
template<typename T>
void foo(T value)
{
}
template<typename T>
void foo()
{
foo(std::numeric_limits<T>::infinity());
}
并像往常一样称呼它foo<float>();
我没有使用
专业化,而是在没有"模板"关键字的情况下进行重载,如下所示:
template<typename T>
void foo(T value)
{
}
void foo(float value)
{
}
我在gcc和Visual Studio 2012中使用它们。
相关文章:
- .cpp和.h文件中的模板专用化声明
- C/C++编译器通常会删除重复的库吗
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- Win32编译器选项和内存分配
- 类模板部分专用化:编译器错误
- 模板专用化与编译器优化
- 模板专用化的不同编译器行为
- 模板函数专用化的内部编译器错误
- MSVC 编译器实例化函数模板的默认定义,即使存在专用化
- 使用类的特定模板专用化时的编译器警告
- G++:有哪些方法可以找出编译器选择了哪个模板专用化
- C++编译器忽略具有模板化类型的类专用化
- SFINAE:编译器不选择专用模板类
- 无法专用化函数模板编译器错误
- 为什么编译器在定义类似的模板专用化时不会出错?
- 在 Visual C++ 下使用模板专用化时编译器错误
- 无法引用专用静态成员变量:编译器错误
- 编译器选择了错误的模板函数专用化
- 如何使编译器使用正确的模板专用化
- 专用嵌套类的静态函数会导致编译器错误 C3855 (MSVC9)