Aggregate initialization除其他事项外,还需要没有用户提供的构造函数。但是 std::tuple
和 std::pair
对有一大组 overloaded constructors .从核心语言的角度来看,这些构造函数是用户提供还是用户声明?
使用 C++17 可以编写(更新/说明:其中 nocopy 是不能复制或移动的类,例如 std::mutex
)
auto get_ensured_rvo_str(){
return std::pair(std::string(),nocopy());
}
编辑:不,这是不可能的,如答案链接和下面的答案中所述。
这需要聚合初始化(对于上下文:Multiple return values (structured bindings) with unmovable types and guaranteed RVO in C++17)。
tuple
和 pair
是否由特殊的标准语言支持以允许这样做(在存在构造函数的情况下)? :
20.5.2.1 Construction
... EXPLICIT constexpr tuple(const Types&...);
6 Effects: The constructor initializes each element with the value of the corresponding parameter.
或者我们原则上可以编写自己的元组
或对
吗?
最佳答案
不,tuple
或 pair
不支持将 no-move 类型传递给它们的构造函数,正如您所观察到的那样,因为构造函数参数和元组(或对)成员可以被观察到是不同的对象:
// exposition only
template<class... Us>
tuple(Us&&... us) : values{std::forward<Us>(us)...} {}
^^ these
^^^^^^ are different objects to these
你必须使用分段构造:
return std::pair<std::string, nocopy>(std::piecewise_construct,
std::forward_as_tuple(), std::forward_as_tuple());
Matt Calabrese 制作了一个 interesting point在 std-proposals 列表上,现在我们已经保证了 RVO,应该可以编写接受工厂的组件来有效地构建它们的成员:
// hypothetical factory constructor
return std::pair(std::factory_construct,
[] { return std::string{}; }, [] { return nocopy{}; });
另一个可能的方向是从 tuple
和 pair
中删除构造函数(或者,更现实地说,编写没有构造函数的类似组件)并依赖于 new extensions to aggregate initialization这应该允许通过多重继承实现 tuple
和 pair
的聚合初始化。 Example .
关于c++ - std::tuple 和 std::pair 是否支持聚合初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38392092/