gpt4 book ai didi

c++ - clang 与 gcc CRTP : constexpr variable cannot have non-literal type

转载 作者:太空狗 更新时间:2023-10-29 21:34:26 28 4
gpt4 key购买 nike

我这里有一个 CRTP 模板类:

template <typename S>
class Base
{
public:
constexpr static S NOT_SET{0};
};

struct Derived : public Base<Derived>
{
};

Clang (5.0.0) 不接受这个:

5 : <source>:5:24: error: constexpr variable cannot have non-literal type 'const Derived'
constexpr static S NOT_SET{0};
^
8 : <source>:8:25: note: in instantiation of template class 'Base<Derived>' requested here
struct Derived : public Base<Derived>
^
5 : <source>:5:24: note: incomplete type 'const Derived' is not a literal type
constexpr static S NOT_SET{0};
^
8 : <source>:8:8: note: definition of 'Derived' is not complete until the closing '}'
struct Derived : public Base<Derived>
^
1 error generated.
Compiler exited with result code 1

但是 gcc(在 4.9.2 和 6.2 上测试过)接受它就好了。

如何在 clang 中执行此操作?

最佳答案

当您尝试在类模板 Base 中使用

Derived 时,它不是一个完整的类型,因此您实际上不能那样使用它。那是因为类型必须是完整的才能声明该类型的变量。没有办法解决它。
总而言之,一个类型在结束时完成 }(以及与您的情况无关的其他异常,例如在其成员函数中)。
这是标准所说的 ( working draft ):

A class is considered a completely-defined object type (or complete type) at the closing } of the class-specifier.
Within the class member-specification, the class is regarded as complete within function bodies, default arguments, noexcept-specifiers, and default member initializers (including such things in nested classes).
Otherwise it is regarded as incomplete within its own class member-specification.

因此 clang 是正确的,错误说的差不多。


如评论中所述,存在一种解决方法。只要派生类型是(让我说)constexpr constructible,您就可以在基类中定义一个 constexpr 函数,返回它的not set 版本(不管它是什么意思).

关于c++ - clang 与 gcc CRTP : constexpr variable cannot have non-literal type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46576847/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com