c++ vector 列表初始值设定项不适用于我的类的类型转换构造函数

标签 c++ boost vector

我创建了一个带有“类型转换构造函数”(采用不同类型的单个参数的构造函数)的类。我无法使用列表初始化语法来创建该类的 vector 。

在 Boost Variant 中包装我的类以某种方式使同一个类使用相似的语法工作。

要使用列表初始化语法将我的类添加到 vector 中,我至少需要做什么?

完整程序:

#include <boost/variant.hpp>
#include <iostream>
#include <string>
#include <vector>

using namespace std;
using boost::variant;

struct S {
  string s;
  S() {}
  ~S() {}
  S(const string& _s) : s(_s) {
    // Type converting constructor.
  }
};

int main() {
  // This works.
  S x{"abcd"};
  cout << "x: " << x.s << endl;

  // Why does this not compile?
  // I'm trying to create a vector with a single element in it.
  vector<S> vs{"vec_abcd"};

  // This works.
  vector<boost::variant<string>> vnts{"vnt_abcd0"};
  cout << "vec: " << boost::get<string>(vnts[0]) << endl;
}

最佳答案

您需要另一组大括号才能使用 std::initializer_list 构造函数。

vector<S> vs{"vec_abcd"};

尝试用 const char[] 参数构造 vector ,但该参数不起作用

vector<S> vs{{"vec_abcd"}};

另一方面,使用单个元素初始化列表初始化 vector 。看样子

vector<S> vs{{"vec_abcd"}};
            |^list data ^|
            ^ ctor call  ^

Live Example

此外,如果您想在 vector 中压缩多个 S,您可以使用

vector<S> vs{{"a"}, {"b"}, {"c"}, ..., {"z"}};

每个用逗号分隔的内部大括号对应于 vector 中的每个 S

关于c++ vector 列表初始值设定项不适用于我的类的类型转换构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38461522/

相关文章:

c++ - 如何在c++中实现这个数据结构

c++ - 返回 Boost Graph 中连接的组件子图的列表

c++ - 如何故意删除 boost::shared_ptr?

C++ 无法创建用户定义类的 vector

c++ - 范围修剪 View 实现不适用于反向 View

c++ - 可排序的 QHBoxLayout

c++ - 删除 QComboBox "Drop-Down"动画

c++ - C1001 : An internal error has occurred in the compiler when including <boost/shared_ptr. hpp>

performance - 在 R 中未命名(变为命名)时对向量的分配非常慢

指向对象的指针 vector 中的 C++ 差异