[英]Code compiles with g++ but not clang++ if incomplete type is used in templated function
[英]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
我试图用typedef将std :: function替换为函数指针,例如:
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";
解决了问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.