c – constexpr静态成员什么时候停止成为constexpr?
发布时间:2020-12-16 09:20:38 所属栏目:百科 来源:网络整理
导读:我有这个片段. #include iostream#include stringstruct JustStr { JustStr(const std::string x) : val(x) {} static constexpr bool pred = false; std::string val;};template typename Tclass C { private: T x; public: C(T x_) : x(x_) {} void f() {
我有这个片段.
#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阻止表达式被视为核心常量表达式.
你不能做的事情之一是评估:
在f()中,我们正在评估这个以便查看x.pred是什么(因为它真的是这个 – > x.pred),但f()不是constexpr函数.所以这个要点排除了c.f().如果f()是constexpr,那么这将编译. 在f2()中,我们不会在任何地方对此进行评估,因此该子弹不适用.我们进行左值到右值的转换,但它确实引用了complete non-volatile const object with a preceding initialization,initialized with a constant expression.没有其他条件适用.所以没关系. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |