具有默认成员初始化程序的结构不能在类内部,并且不能用作默认参数

问题描述

以下代码无法编译:

info

我收到以下错误

#include <iostream>

struct toto {
  struct options final {
    bool option1 = false;
    bool option2 = false;
  };

  static void func(const options &opt = {}) {
    std::cout << "option1 = " << opt.option1 << std::endl;
    std::cout << "option2 = " << opt.option2 << std::endl;
  }
};

int main() {
  toto::func();
}

但是,如果我将选项结构移到封闭的to结构之外,它将编译:

test-default-member-init.cc:12:42: error: default member initializer for 'option1' needed within deFinition of enclosing class 'toto' outside of member functions
  static void func(const options &opt = {}) {
                                         ^
test-default-member-init.cc:8:10: note: default member initializer declared here
    bool option1 = false;
         ^
test-default-member-init.cc:19:14: error: too few arguments to function call,single argument 'opt' was not specified
  toto::func();
  ~~~~~~~~~~ ^
test-default-member-init.cc:12:3: note: 'func' declared here
  static void func(const options &opt = {}) {
  ^
2 errors generated.

我在OSX上使用clang,并以此方式编译代码段:

#include <iostream>

struct options final {
  bool option1 = false;
  bool option2 = false;
};

struct toto {
  static void func(const options &opt = {}) {
    std::cout << "option1 = " << opt.option1 << std::endl;
    std::cout << "option2 = " << opt.option2 << std::endl;
  }
};

int main() {
  toto::func();
}

有人可以解释一下为什么第一个被剪掉的代码无法编译,以及是否有任何解决方案可以使它正常工作?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)