加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么不能将lambda转换为函数指针,在constexpr上下文中使

发布时间:2020-12-16 05:30:22 所属栏目:百科 来源:网络整理
导读:考虑一个例子: template void (*Foo)()struct S {};int main() { struct A { static void x() { } }; SA::x s;} 代码编译在clang中,gcc认为x没有链接… 对于非常类似的例子,只是当使用lambda表达式时: template void (*Foo)()struct S {};int main() { aut
考虑一个例子:
template <void (*Foo)()>
struct S {
};

int main() {
    struct A {
        static void x() { }
    };
    S<&A::x> s;
}

代码编译在clang中,gcc认为x没有链接…
对于非常类似的例子,只是当使用lambda表达式时:

template <void (*Foo)()>
struct S {
};

int main() {
    auto lambda = []{};
    S<+lambda> s;
}

gcc和clang同意不编译代码:根据gcc,一元函数返回的函数没有链接,相反,cast运算符对该函数没有声明为constexpr.有没有理由不允许lambda转换为在constexpr上下文中使用的函数指针?

查找编译器生成的以下错误和现场演示:

gcc:

prog.cc:7:14: error: ‘main()::::_FUN’ is not a valid template argument for type ‘void (*)()’ because ‘static constexpr void main()::::_FUN()’ has no linkage

clang:

prog.cc:7:8: note: non-constexpr function ‘operator void (*)()’ cannot be used in a constant expression

解决方法

ang hasn’t implemented constexpr lambdas yet.

海湾合作委员会在其他方面落后. [temp.arg.nontype]/2唯一有趣的约束是参数是一个常数表达式.但[expr.const]/(5.2)使它成为一个,所以这是完全有效的.也许海湾合作委员会还没有实施N4198,这消除了联动要求.

请注意,constexpr lambdas和no-linkage函数指针模板参数都是Post C 14功能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读