我遇到了一个看似违反直觉的错误,即无法将constexpr函数的值赋给constexpr文字(希望我正在使用正确的语言).这是一个例子:
class MyClass {
public:
static constexpr int FooValue(int n) { return n + 5; }
static constexpr int Foo5 = FooValue(5); // compiler error
static constexpr int Foo5Alt(void) { return FooValue(5); } // OK
};
Run Code Online (Sandbox Code Playgroud)
在GCC 4.8.4中,Foo5标记为field initializer is not constant.发现这个帖子暗示旧版本的GCC可能是罪魁祸首.所以我把它插入Coliru(GCC 6.2.0)并得到了错误'static constexpr int MyClass::FooValue(int)' called in a constant expression before its definition is complete.我添加Foo5Alt()了将其值作为constexpr函数返回而不是文字,并且编译得很好.
我想我不遵循为什么FooValue(5)不能用作初始化器Foo5.定义FooValue(int …
这部分是一个风格问题,部分是一个正确性问题。提交以下示例(处理包含嵌入标头的数据块的类的精简):
class Foo {
public:
Foo(size_t size)
: scratch_(new uint8_t[header_length_ + size]),
size_(header_length_ + size) {
}
~Foo() {
delete[] scratch_;
}
Foo(const Foo&) = delete; // Effective C++
void operator=(const Foo&) = delete; // Effective C++
protected:
struct Header {
uint32_t a, b, c, d;
};
uint8_t * const scratch_;
size_t const size_;
Header * const header_ = reinterpret_cast<Header *>(scratch_);
static constexpr size_t header_length_ = sizeof(Header);
static constexpr size_t data_offset_ = header_length_;
size_t const data_length_ = size_ - data_offset_; …Run Code Online (Sandbox Code Playgroud)