我想要一个constexpr从constexpr函数计算的值(即编译时常量).我想要将这两个作用于类的命名空间,即静态方法和类的静态成员.
我第一次写这个(对我来说)明显的方式:
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) 为什么下面的代码不能编译?
#include <stdint.h>
#include <array>
class A
{
struct Helper
{
static constexpr uint64_t p2(uint8_t n)
{
return static_cast<uint64_t>(1) << n;
}
};
using DenomArray = std::array<uint64_t, Helper::p2(5)>;
};
Run Code Online (Sandbox Code Playgroud)
使用 GCC 我得到:
error: 'static constexpr uint64_t A::Helper::p2(uint8_t)' called in a constant expression before its definition is complete
Run Code Online (Sandbox Code Playgroud)
我的理解是p2应该定义函数,因为Helper类是完全编译的。
为 x86 和 GCC 12 尝试了 MSVC 编译器版本 19.29.30040。
编辑1:
模板和非模板类的行为不同。例如下面的代码编译:
template <class T>
class A
{
private:
struct Helper
{
static constexpr T p2(uint8_t n)
{
return …Run Code Online (Sandbox Code Playgroud)