【问题标题】:explicitly defaulted function cannot be declared as constexpr because the implicit declaration is not constexpr不能将显式默认函数声明为 constexpr,因为隐式声明不是 constexpr
【发布时间】:2017-10-15 14:45:27
【问题描述】:

我正在尝试编译一个 C++ 库(使用 gcc 5.3.1-14ubuntu2)并遇到这种类型的错误:

> In file included from
> /root/pitchfork/workspace/unanimity/include/pacbio/consensus/ModelConfig.h:49:0,
>                  from /root/pitchfork/workspace/unanimity/src/models/P6C4NoCovModel.cpp:42:
> /root/pitchfork/workspace/unanimity/include/pacbio/data/internal/BaseEncoding.h:119:31:
> error: explicitly defaulted function 'constexpr
> PacBio::Data::detail::NCBI2na&
> PacBio::Data::detail::NCBI2na::operator=(const
> PacBio::Data::detail::NCBI2na&)' cannot be declared as constexpr
> because the implicit declaration is not constexpr:
>      inline constexpr NCBI2na& operator=(const NCBI2na&) = default;

导致麻烦的代码部分是:

class NCBI2na
{
public:
    static inline constexpr NCBI2na FromASCII(const char base) { return NCBI2na{base}; }
    static inline constexpr NCBI2na FromRaw(const uint8_t raw) { return NCBI2na{raw}; }

public:
    ~NCBI2na() = default;

    inline constexpr NCBI2na(const NCBI2na&) = default;
    inline constexpr NCBI2na(NCBI2na&&) = default;

    inline constexpr NCBI2na& operator=(const NCBI2na&) = default;
    inline constexpr NCBI2na& operator=(NCBI2na&&) = default;    
};

似乎引起麻烦的代码部分是“= default”。这也可能是相关的

我环顾四周,但到目前为止找不到解决此问题的方法。 以下是一些可能有所帮助的类似问题:

constexpr defining static data member of literal type that is declared const constructor of derived class cannot be constexpr if base class contains array member

【问题讨论】:

  • It works 与 GCC 7.2.0 以及 Clang 3.8.0。

标签: c++ constexpr


【解决方案1】:

这似乎是一个 GCC 错误。假设您编译为 C++14,那么编写的规则如下:

[dcl.constexpr]/3

constexpr 函数的定义应满足以下条件 约束:

  • 它不能是虚拟的
  • 它的返回类型应该是文字类型;
  • 它的每个参数类型都应该是文字类型;
  • 其函数体应为 = delete、= default 或 ...

实际上,您向我们展示的代码满足了上述所有条件。所以你的赋值运算符定义没问题,应该被接受为constexpr


此代码(一旦错误导致静态函数被注释掉),被GCC 5.4.0 接受。因此,您绝对可以将其归结为编译器错误。

【讨论】:

  • 所以您认为使用 GCC 5.4.0 编译应该可以工作?
  • @ThomasCokelaer - 我的附录中的链接是一个在线编译器。
  • 太棒了。我错过了链接。我可以使用 GCC 5.3.0 重现错误。
猜你喜欢
  • 2017-10-13
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 2022-09-23
  • 1970-01-01
  • 2012-07-19
相关资源
最近更新 更多