【发布时间】:2020-12-10 12:15:45
【问题描述】:
为什么这段代码 sn-p 可以在 C++17 中使用,而编译器在使用 C++11 时会报错(即https://godbolt.org/z/71G91P)? 这段代码 sn-p 有什么潜在的问题吗?
#include<iostream>
class ctx
{
public:
int map_create(void*){std::cout << "haha" << std::endl; return 0;};
};
ctx obj;
typedef int (ctx::*ctx_mem_func)(void*);
template <ctx_mem_func func>
int regHelper(void*)
{
((&obj)->*func)(nullptr);
return 0;
}
constexpr ctx_mem_func testFunc = &ctx::map_create;
typedef int(*callBackFunc)(void*);
int reg(callBackFunc)
{
return 0;
}
int main()
{
reg(regHelper<testFunc>);
//But this expression is ok.
reg(regHelper<&ctx::map_create>);
std::cout << "this is a test" << std::endl;
}
以下是使用 c++11(gun 10.0.2) 时的错误信息:
<source>: In function 'int main()':
<source>:30:28: error: no matches converting function 'regHelper' to type 'callBackFunc {aka int (*)(void*)}'
reg(regHelper<testFunc>);
^
<source>:13:5: note: candidate is: template<int (ctx::* func)(void*)> int regHelper(void*)
int regHelper(void*)
^
【问题讨论】:
-
"编译器抱怨"....什么编译器?在什么模式下?在哪里? edit 完整引用所有错误!
-
我在使用 c++17 (godbolt.org/z/vKn87Y) 时也遇到错误。你用的是什么编译器?你得到什么错误?
-
除非 C++17 在某些情况下将
constexpr模板参数的要求放宽为纯const表达式,否则这不会成功。 -
在询问构建错误时,请始终在问题中包含完整和完整的错误输出,并以文本形式复制粘贴。还要在代码中出现错误的行中添加 cmets。并告诉我们您如何构建程序,提供的所有选项和标志。并且请在问题本身中包含所有相关信息独立提出问题。
-
这里是测试:godbolt.org/z/71G91P。编译器抱怨。