聚合初始化 http://en.cppreference.com/w/cpp/language/aggregate_initialization除其他外还需要没有用户提供的构造函数. But std::tuple
and std::pair
对有一大套重载构造函数 http://en.cppreference.com/w/cpp/utility/tuple/tuple。从核心语言来看,这些构造函数是用户提供的甚至用户声明的 ?
使用 C++17 可以编写(更新/澄清:其中 nocopy 是无法复制或移动的类,例如std::mutex
)
auto get_ensured_rvo_str(){
return std::pair(std::string(),nocopy());
}
编辑:不,正如链接的答案和下面的答案中所解释的那样,这是不可能的。
这需要聚合初始化(对于上下文:C++17 中具有不可移动类型和有保证的 RVO 的多个返回值(结构化绑定) https://stackoverflow.com/questions/38385451/multiple-return-values-structured-bindings-with-unmovable-types-or-guaranteed).
Are tuple
and pair
由特殊标准语言支持以允许这样做(在存在构造函数的情况下)? :
20.5.2.1 构建
...
显式 constexpr tuple(const Types&...);
6
效果:
构造函数使用以下值初始化每个元素
相应的参数。
或者我们原则上可以编写自己的tuple
or pair
?
不,没有支持tuple
or pair
用于将不可移动类型传递给其构造函数,正如您所观察到的那样,不可能存在,因为构造函数参数和元组(或对)成员可以观察到不同的物体:
// 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());
马特·卡拉布雷斯做了一个有趣的一点 https://isocpp.org/forums/iso-c-standard-future-proposals?place=msg%2Fstd-proposals%2FJ62lsMB6Egc%2F38M9WKYvCQAJ在 std-proposals 列表中,现在我们已经保证 RVO 应该可以编写接受工厂以有效地就地构造其成员的组件:
// hypothetical factory constructor
return std::pair(std::factory_construct,
[] { return std::string{}; }, [] { return nocopy{}; });
另一个可能的方向是从中删除构造函数tuple
and pair
(或者,更现实地说,编写没有构造函数的类似组件)并依赖于聚合初始化的新扩展 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0017r0.html应该允许聚合初始化tuple
and pair
通过多重继承实现。Example http://melpon.org/wandbox/permlink/63SPQHgu1myz3Twi.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)