下面是将元素添加到包含std::pair
的向量中的代码
std::vector<std::pair<std::string, std::type_index>> args_;
template <class T>
inline OperationEntry& setArg(const std::string& name)
{
args_.push_back({name, typeid(T)});
return *this;
}
如何将元素添加到包含std::tuple
的向量中?
std::vector<std::tuple<std::string, std::type_index, Attribute>> args_;
template <class T>
inline OperationEntry& setArg(const std::string& name, Attribute value = Attribute())
{
args_.push_back({name, typeid(T), value});
return *this;
}
我尝试了args_.push_back(std::make_tuple(name, typeid(T), value));
我收到此错误:
[GCC] converting to
‘std::vector<std::tuple<std::__cxx11::basic_string<char,
std::char_traits<char>, std::allocator<char> >, std::type_index,
mv::Attribute> >::value_type {aka
std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::type_index, mv::Attribute>}’ from
initializer list would use explicit constructor ‘constexpr std::tuple<
<template-parameter-1-1> >::tuple(_UElements&& ...) [with _UElements =
{const std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char> >&, const std::type_info&, mv::Attribute&};
<template-parameter-2-2> = void; _Elements =
{std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::type_index, mv::Attribute}]’
答案 0 :(得分:4)
std::array<std::array<int, 2>, 2>
在N4387之前,用于上述初始化的args_.push_back({name, typeid(T), value});
的构造函数是无条件std::tuple
的,并且如果通过复制列表初始化中的重载决议选择了该编译器,则可以引发错误。
explicit
上述调用将尝试为不可复制的args_.push_back(std::make_tuple(name, typeid(T), value));
实例使用复制构造函数。
为了在N4387之前的实现中构造元组,请使用std::type_info
:
emplace_back
或推回可复制构造类型的元组:
args_.emplace_back(name, typeid(T), value);