Do std::tuple and std::pair support aggregate initialization?

百般思念 提交于 2019-12-05 04:07:21

No, there is no support in tuple or pair for passing no-move types to their constructors, and as you've observed there cannot be, since the constructor argument and tuple (or pair) member can be observed to be different objects:

// exposition only
template<class... Us>
tuple(Us&&... us) : values{std::forward<Us>(us)...} {}
              ^^ these
                    ^^^^^^ are different objects to these

You would have to use piecewise construction:

return std::pair<std::string, nocopy>(std::piecewise_construct,
    std::forward_as_tuple(), std::forward_as_tuple());

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{}; });

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!