作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有以下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 编译它时,出现以下错误:
..\check2\main.cpp(5) : error C2589: '::' : illegal token on right side of '::'
..\check2\main.cpp(5) : error C2059: syntax error : '::'
如果我不包含特化 foo<float>
,程序编译正常.该代码还可以在 gcc 4.8.4 下编译得很好包括特化,这表明 Visual C++ 编译器存在一些问题。
代码是否正确,是否应该编译?是否有适用于 Visual 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>();
关于c++ - 在 Visual C++ 下使用模板特化时出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35583062/
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 4 年前。
正如您在 this travis.yml 中看到的那样文件,我的代码依赖于一些第三方库,我在构建项目之前将它们安装在远程系统上。 Travis 每次推送提交时都会下载并构建这些库,这可以避免吗?我的意
我是一名优秀的程序员,十分优秀!