do std :: tuple和std :: pair支持聚合初始化? [英] Do std::tuple and std::pair support aggregate initialization?

查看:355
本文介绍了do std :: tuple和std :: pair支持聚合初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

聚合初始化需要用户提供的构造函数。但是 std :: tuple std :: pair 对有大的重载的构造函数。从核心语言的角度来看,这些构造函数是用户提供的还是用户声明的

Aggregate initialization requires among other things no user-provided constructors. But std::tuple and std::pair pair have a large set of overloaded constructors. From the point of the core language, are these constructors user-provided or even user-declared ?

(更新/澄清:其中nocopy是不能被复制或移动的类,例如 std :: mutex )。 p>

With C++17 it will be possible to write (update/clarification: where nocopy is a class that can not be copied or moved, such as std::mutex)

auto get_ensured_rvo_str(){
   return std::pair(std::string(),nocopy());
}

编辑:不,链接到答案和以下答案。

edit: no, it's not possible as explained in the linked to answers and the answer below.

这需要聚合初始化(对于上下文:使用C ++ 17中的不可移动类型或保证RVO的多个返回值)

which requires aggregate initialization (for context: Multiple return values (structured bindings) with unmovable types or guaranteed RVO in C++17).

由特殊支持的 tuple 标准语言允许这种(在构造函数的情况下)? :

Are tuple and pair backed by special standard language to allow this (in presence of constructors) ? :


20.5.2.1建设

20.5.2.1 Construction

...
EXPLICIT constexpr tuple(const Types& ...);

... EXPLICIT constexpr tuple(const Types&...);

6
效果:
构造函数用
对应参数的值初始化每个元素。

6 Effects: The constructor initializes each element with the value of the corresponding parameter.

或者我们原则上可以写我们自己的 tuple pair

or can we in principle write our own tuple or pair?

不, tuple中不支持

解决方案

推荐答案

// 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制作了有趣的点,现在我们已经保证RVO应该可以写

Matt Calabrese made an interesting point on the std-proposals list that now we have guaranteed RVO it should be possible to write components that accept factories to construct their members effectively inplace:

// hypothetical factory constructor
return std::pair(std::factory_construct,
    [] { return std::string{}; }, [] { return nocopy{}; });

另一个可能的方向是从 tuple pair (或者,更现实地,写没有构造函数的工作组件),并依赖于新扩展的聚合初始化,应该允许 tuple pair 通过多继承实现。 示例

Another possible direction would be to remove the constructors from tuple and pair (or, more realistically, to write workalike components without constructors) and rely on the new extensions to aggregate initialization that should permit aggregate initialization of tuple and pair implemented via multiple-inheritance. Example.

这篇关于do std :: tuple和std :: pair支持聚合初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆