c++ - 静态 constexpr 成员变量初始化

标签 c++ c++14 constexpr

我有以下代码:

struct Foo
{       
    struct Bar
    {
        std::uint32_t x = -1;

        constexpr Bar(std::uint32_t x) : x(x) {}
    };

    static constexpr Bar CONST_BAR = Bar(0);
};

当我尝试编译它时,出现以下错误:

error: ‘constexpr Foo::Bar::Bar(uint32_t)’ called in a constant expression before its definition is complete



有人可以向我解释发生了什么吗?据我所知,Bar 的构造函数是在第一次调用之前定义的。

Live example

最佳答案

我没有详细的解释,但我碰巧也偶然发现了这个问题,并认为它至少值得一提......除了放置CONST_BAR的定义之外。结构之外 Foo ,另一种可能的解决方法是实例化 Foo :

// Example program
#include <iostream>
#include <string>

template<typename T = void>
struct Foo
{       
    struct Bar
    {
        std::uint32_t x = -1;
    
        constexpr Bar(std::uint32_t x) : x(x) {}
    };
    
    static constexpr Bar CONST_BAR = Bar(0);
};

int main()
{
    std::cout << "x: " << Foo<>::CONST_BAR.x << "\n";
}

关于c++ - 静态 constexpr 成员变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62147479/

相关文章:

c++ - 在 C++ 中初始化为 NULL 的字符串

c++ - 使用 std::vector<> 和 std::shared_ptr<> 会导致错误

C++:实例化库中的许多模板

c++ - C++:在constexpr构造函数中初始化成员数组

c++ - 无 ODR 使用的完美转发

c++ - 将 friend 声明注入(inject)命名空间,Eckel,Vol1,pg :440?

c++ - 是否可以通过一个函数调用将统一数据发送到GLSL中的结构

c++ - vector 插入后丢失数据

c++11 - std::move-如何警告程序员不要使用* move 自*对象

c++ - Constexpr 成员函数