c++ - constexpr 静态成员什么时候不再是 constexpr?

标签 c++ c++17 constexpr if-constexpr

我有这个片段。

#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("yes")); 不应该同时失败或成功吗?为什么一个失败,为什么另一个成功?

最佳答案

有一个list of things防止表达式被视为核心常量表达式。

您不能做的一件事是评估:

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

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

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

关于c++ - constexpr 静态成员什么时候不再是 constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50067414/

相关文章:

c++ - 具有非成员函数的 std::vector 中的多态性

c++ - 尽管包含 <typeinfo> ,但 Clang 拒绝 type_info 为不完整

c++ - C++ 中哪些类型被认为是可调用的?

c++ - constexpr-if-else 主体能否在 constexpr auto 函数中返回不同类型?

c++ - 模板;构造函数;编译时间

c++ - 对象必须包含指针成员才能与其他对象通信吗?

C++17 lambda 捕获 *this

c++ - constexpr 指针值

c++ - C++ constexpr编译问题

c++ - pthread_create : Passing argument by value