c++ - std::function of a value templated method 使用 clang 和 g++ 编译,但不使用 msvc

标签 c++ templates gcc visual-c++ clang

以下代码compiles with 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

我尝试将 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";

解决了问题。

关于c++ - std::function of a value templated method 使用 clang 和 g++ 编译,但不使用 msvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751767/

相关文章:

c++ - 以不同方式替换每个项目,regex c++

c++ - 如何在专门化交换功能时使用 gcc8 修复编译错误/

c++ - 错误 : no matching function for call to ‘BSTreeNode<int, int>::BSTreeNode(int, int, NULL, NULL)’ - what's wrong?

linux - C 中意外的段错误

c++ - 调用非虚拟成员时消除基类歧义

c++ - 在编译时对整数常量元组进行排序

c++ - 什么时候删除模板实例比删除非模板重载更可取?

c++ - 在没有隐式转换的情况下在编译时检测运算符

gcc - 为什么 gcc 不将 _mm256_loadu_pd 解析为单个 vmovupd?

c++读取数组中的每3个元素