【问题标题】:Why this code snippet works with C++17 whereas the compiler complains when using C++11?为什么此代码片段适用于 C++17,而编译器在使用 C++11 时会报错?
【发布时间】: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。编译器抱怨。

标签: c++ c++11 templates c++17


【解决方案1】:

这是 C++14 和 C++17 的区别。 Simplified:

int f();
template<int (&)()> struct S {};
constexpr auto& q = f;
using R = S<q>; // valid in C++17, invalid in C++14

更改为 Allow constant evaluation for all non-type template arguments,这意味着现在可以将命名函数(成员函数等)的 constexpr 变量用作 NTTP,而以前只允许函数的实际名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-12
    • 2023-03-27
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多