std::value templated 方法的函数使用 clang 和 g++ 进行编译,但不使用 msvc 进行编译
std::function of a value templated method compiles with clang and g++ but not with msvc
以下代码使用 clang v5.0.0 和 g++ v8.1.0 编译,但在 Visual Studio (2013 和 2017( 中失败:
#include <string>
#include <functional>
#include <iostream>
template <const char* name>
std::string fct() {
return name;
}
const char toto[] = "toto";
std::function<std::string()> fctptr = fct<toto>;
int main(){
std::cout << fctptr() << std::endl;
}
错误如下:
main.cpp(11): error C2440: 'initializing' : cannot convert from 'std::string (__cdecl *)(void)' to 'std::function<std::string (void)>'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
我试图将 std::function 替换为指向函数指针的 typedef,如下所示:
typedef std::string(*Fctptr)();
Fctptr fctptr = fct<toto>;
但是,我得到了同样的错误。
是 msvc 编译器的错误,还是上面的代码不符合标准。
FWIW,以下无法使用 g++ 6.4.0 (g++ -std=c++11
( 编译失败。
#include <string>
#include <functional>
#include <iostream>
template <const char* name>
std::string fct() {
return name;
}
const char toto[] = "toto";
std::function<std::string()> fctptr = fct<toto>;
int main(){
std::cout << fctptr() << std::endl;
}
下面是错误消息:
socc.cc:11:43: error: the value of ‘toto’ is not usable in a constant expression
std::function<std::string()> fctptr = fct<toto>;
^~~~
socc.cc:10:12: note: ‘toto’ was not declared ‘constexpr’
const char toto[] = "toto";
将toto
的定义更改为
constexpr char toto[] = "toto";
解决了问题。
相关文章:
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 为什么 gcc 编译这个而 msvc 没有
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- MSVC 无法编译 SFINAE 检查
- 可变参数模板未在 MSVC 中编译?
- MSVC 2010 编译应用程序和 MSVC 2019 编译应用程序之间的行为差异
- 如何使用CLion和MSVC编译器工具链编译wxWidgets Hello World应用程序而没有错误?
- 使用 msvc 15 在 Qt5.13 中编译 CUDA 代码
- std::value templated 方法的函数使用 clang 和 g++ 进行编译,但不使用 msvc 进行编译
- 使用MSVC编译的Qt程序在app.exec()上崩溃
- 使用 MSVC 编译时,msdpb* 文件的正确用法是什么?
- constexpr 函数中的 for 循环无法使用 MSVC 19.23 进行编译
- 私有运营商删除会触发 GCC 和 Clang 的编译时错误,但不会在 MSVC 上触发编译时错误
- variadic模板代码中的GCC VS MSVC编译误差
- C2064 从 MSVC v100 更新到 v140 平台工具集时出现编译错误
- GCC 和 clang 抛出"no matching function call"但 msvc (cl) 按预期编译和工作
- 链接错误时,使用CLION/CMAKE/MSVC 2015编译WIN32应用程序
- 强制完成模板编译(MSVC/ g++)
- 在windows上编译MSVC是严格必要的吗?
- 用clang编译MSVC std库.在类范围内显式的模板函数特化