相关疑难解决方法(0)

constexpr使用静态函数初始化静态成员

要求

我想要一个constexprconstexpr函数计算的值(即编译时常量).我想要将这两个作用于类的命名空间,即静态方法和类的静态成员.

第一次尝试

我第一次写这个(对我来说)明显的方式:

class C1 {
  constexpr static int foo(int x) { return x + 1; }
  constexpr static int bar = foo(sizeof(int));
};
Run Code Online (Sandbox Code Playgroud)

g++-4.5.3 -std=gnu++0x 对此说:

error: ‘static int C1::foo(int)’ cannot appear in a constant-expression
error: a function call cannot appear in a constant-expression
Run Code Online (Sandbox Code Playgroud)

g++-4.6.3 -std=gnu++0x 抱怨:

error: field initializer is not constant
Run Code Online (Sandbox Code Playgroud)

第二次尝试

好吧,我想,也许我必须把事情从课堂上移开.所以我尝试了以下方法:

class C2 {
  constexpr static int foo(int x) { return x + 1; }
  constexpr static int bar;
}; …
Run Code Online (Sandbox Code Playgroud)

c++ gcc g++ static-members constexpr

31
推荐指数
2
解决办法
3万
查看次数

将静态constexpr类成员分配给运行时变量

我知道有很多类似的问题,但不知何故有不同的问题.这是关于以下情况:

#include <iostream>
#include <array>

template<typename T> class MyClass
{
public:
    static constexpr std::array<T,4> ARRAY {{4, 3, 1, 5}};
};

int main()
{
    constexpr std::array<int, 4> my_array(MyClass<int>::ARRAY); // works fine -> can use the ARRAY to initialize constexpr std::array

    constexpr int VALUE = 5*MyClass<int>::ARRAY[0]; // works also fine

    int value;
    value = my_array[0]; // can assign from constexpr
    value = MyClass<int>::ARRAY[0]; // undefined reference to `MyClass<int>::ARRAY

    std::cout << VALUE << std::endl;
    std::cout << value << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

据我所知 …

c++ templates one-definition-rule constexpr c++11

8
推荐指数
1
解决办法
894
查看次数