【问题标题】:c++11 struggling to understand why I can't uniform init a structure, but I can init a std::pair of similar typec++11 努力理解为什么我不能统一初始化一个结构,但我可以初始化一个类似类型的 std::pair
【发布时间】:2019-03-27 15:18:18
【问题描述】:

给定以下代码:

#include <functional>
#include <string>
#include <iostream>

class test
{
public:
    struct info
    {
        std::string name {""};
        std::function<bool()> func;
    };

    //info my_info { "test_name", [&]{return member_func();} }; // <------ ERROR HERE

    std::pair<std::string, std::function<bool()>> my_info_pair { "test_name", [&]{return member_func();} };

    bool member_func()
    {
        std::cout << "member_func\n";
        return true;
    };

};

int main() {
    std::cout << "start\n";
    test t;
    std::cout << t.my_info_pair.first << std::endl;
    t.my_info_pair.second();
    std::cout << "end\n";
}

此代码有效。但是,如果我取消注释注释掉的行 - 它试图以与 std::pair 初始化相同的方式初始化 info 结构,那么它会失败。我不知道为什么...

得到的错误是:

prog.cc:15:60: error: could not convert '{"test_name", <lambda closure
object>test::<lambda()>{((test*)this)}}' from '<brace-enclosed
initializer list>' to 'test::info'
     info my_info { "test_name", [&]{return member_func();} };
                                                             ^

链接到我的测试代码:here (wandbox)

【问题讨论】:

  • 为什么是std::string name {""};,而不是std::string name;
  • @AlgirdasPreidžius 我猜只是为了给它一个默认值....但实际上这可能不是必需的...:o
  • @AlgirdasPreidžius 哦,等等……这使它起作用了! ...呃,困惑!
  • @code_fodder 1) "给它一个我猜的默认值" 但是,std::string 有默认构造函数,它构造一个空字符串.. 2) "这就让它起作用了!”这就是我问这样一个问题的原因:)
  • @AlgirdasPreidžius 啊,很酷 - 请添加作为答案(也许有一个简短的解释为什么它错了?)我会标记它:)

标签: c++ c++11 uniform-initialization aggregate-initialization


【解决方案1】:

这里的问题是

std::string name {""};

您使用类成员初始化程序,而在 C++11 中,如果您希望对象成为聚合对象(根据 [dcl.init.aggr]/1),则不允许这样做。要让它在 C++11 中编译,你必须删除它。

在 C++14 及更高版本中,该约束已被删除(更新 [dcl.init.aggr]/1),并且在聚合中允许使用类成员初始化器,并且代码将按原样编译。

【讨论】:

  • 也许使用cppreference 链接代替(或另外)。 N3337有点老了。
  • @1201ProgramAlarm 我链接到旧的,因为 Q 被标记为 C++11。这样他们就可以看到 C++11 语言。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多