c – constexpr静态成员什么时候停止成为constexpr?

c – constexpr静态成员什么时候停止成为constexpr?,第1张

概述我有这个片段. #include <iostream>#include <string>struct JustStr { JustStr(const std::string& x) : val(x) {} static constexpr bool pred = false; std::string val;};template <typename T>cla 我有这个片段.

#include <iostream>#include <string>struct JustStr {    JustStr(const std::string& x) : val(x) {}    static constexpr bool pred = false;    std::string val;};template <typename T>class C { private:    T x; public:    C(T x_) : x(x_) {}    voID f() {        if constexpr (!x.pred) {                std::cout << x.val << std::endl;            }    }};template<typename T>voID f2(T x) {    T y(x);    if constexpr (!y.pred) {            std::cout << x.val << std::endl;        }}int main() {    C<JustStr> c(JustStr("yes"));    c.f();  // Fails    f2(JustStr("yes"));  // Succeeds    return 0;}

我的问题是:不应该c.f();和f2(JustStr(“是”));失败或同时成功?为什么一个失败了,为什么另一个失败?

解决方法 有一个 list of things阻止表达式被视为核心常量表达式.

你不能做的事情之一是评估:

this,except in a constexpr function or a constexpr constructor that is being evaluated as part of e;

在f()中,我们正在评估这个以便查看x.pred是什么(因为它真的是这个 – > x.pred),但f()不是constexpr函数.所以这个要点排除了c.f().如果f()是constexpr,那么这将编译.

在f2()中,我们不会在任何地方对此进行评估,因此该子d不适用.我们进行左值到右值的转换,但它确实引用了complete non-volatile const object with a preceding initialization,initialized with a constant expression.没有其他条件适用.所以没关系.

总结

以上是内存溢出为你收集整理的c – constexpr静态成员什么时候停止成为constexpr?全部内容,希望文章能够帮你解决c – constexpr静态成员什么时候停止成为constexpr?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1212004.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存