【发布时间】:2021-08-13 19:38:48
【问题描述】:
为什么下面的代码不能编译?
#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)>;
};
使用 GCC 我得到:
error: 'static constexpr uint64_t A::Helper::p2(uint8_t)' called in a constant expression before its definition is complete
我的理解是应该定义 p2 函数,因为 Helper 类已完全编译。
尝试了用于 x86 和 GCC 12 的 MSVC 编译器版本 19.29.30040。
EDIT1:
模板和非模板类的行为不同。例如下面的代码编译:
template <class T>
class A
{
private:
struct Helper
{
static constexpr T p2(uint8_t n)
{
return static_cast<T>(1) << n;
}
};
using DenomArray = std::array<T, Helper::p2(5)>;
};
using IntA = A<uint64_t>;
【问题讨论】:
-
您应该指定您使用的 C++ 版本(即 c++11、c++14...)
-
TL;骗子的博士:内联类函数的定义不是类定义的一部分。因此,它们不能用于定义类的成员。
-
@AlexisWilke 查看更新后的帖子。
-
我重新打开了Q,这里有一个旧目标的链接供参考:stackoverflow.com/questions/56799393/…。不确定这里是哪个编译器,因为
Helper::p2(5)实际上是A::Helper::p2(5),而A尚未定义。
标签: c++