c++ - constexpr 和奇怪的错误

标签 c++ c++11 constexpr

我有:

constexpr bool is_concurrency_selected()const
    {
        return ConcurrentGBx->isChecked();//GBx is a groupbox with checkbox
    }

我收到错误:

C:\...\Options_Dialog.hpp:129: error: enclosing class of 'bool Options_Dialog::is_concurrency_selected() const' is not a literal type

有什么想法吗?

最佳答案

这意味着您的类不是文字类型...该程序无效,因为Options 不是文字类类型。但是 Checker 是文字类型。

struct Checker {
  constexpr bool isChecked() {
    return false;
  }
};

struct Options {
  Options(Checker *ConcurrentGBx)
    :ConcurrentGBx(ConcurrentGBx)
  { }

  constexpr bool is_concurrency_selected()const
  {
      //GBx is a groupbox with checkbox
      return ConcurrentGBx->isChecked();
  }

  Checker *ConcurrentGBx;
};

int main() {
  static Checker c;
  constexpr Options o(&c);
  constexpr bool x = o.is_concurrency_selected();
}

铿锵打印

test.cpp:12:18: error: non-literal type 'Options' cannot have constexpr members
    constexpr bool is_concurrency_selected()const
                   ^
test.cpp:7:8: note: 'Options' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
    struct Options {

如果您修复此问题并使 Options 构造函数成为 constexpr,我的示例代码片段就会编译。类似的事情可能适用于您的代码。

您似乎不明白constexpr 的含义。我建议阅读一本关于它的书(如果已经有这样的书的话)。

关于c++ - constexpr 和奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9607279/

相关文章:

c++ - Delete[] 导致 C++ 崩溃

c++ - 在静态库中包含 STL

c++ - 将 unique_ptr 的 vector 传递给对象。 vector 成为成员变量。正确的做法?

c# - Visual Studio : C++\CLI wrapper assembly path dependency problems

c++ - 双数的位表示

c++ - static_assert with nonconstexpr objects in hana's tutorial

C++:无法从相同类型的常量初始化枚举值

c++ - constexpr 类中的引用字段

c++ - C++什么时候会出现Incomplete Type错误

c++ - 移动构造对象的 GCC 奇怪行为