簡體   English   中英

值模板化方法的std :: function可使用clang和g ++編譯,但不能使用msvc編譯

[英]std::function of a value templated method compiles with clang and g++ but not with msvc

以下代碼使用clang v5.0.0g ++ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM