我创建了一个带有“类型转换构造函数”(采用不同类型的单个参数的构造函数)的类。我无法使用列表初始化语法来创建该类的 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 ^
此外,如果您想在 vector 中压缩多个 S
,您可以使用
vector<S> vs{{"a"}, {"b"}, {"c"}, ..., {"z"}};
每个用逗号分隔的内部大括号对应于 vector 中的每个 S
。
关于c++ vector 列表初始值设定项不适用于我的类的类型转换构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38461522/