[英]How can I force compiler to use default constructor when adding element to vector using emplace_back?
How can I force compiler to use default constructor when adding element to vector using emplace_back? 使用emplace_back向向量添加元素时,如何强制编译器使用默认构造函数?
#include <vector>
#include <utility>
enum E {E1, E2};
struct A
{
A(){}
A(int i){}
};
int main()
{
std::vector<std::pair<E, A>> testMap;
testMap.emplace_back(E1, 10);
// testMap.emplace_back(E2);
}
Commented out line gives following error: error C2664: 'std::pair<_Ty1,_Ty2>::pair(const std::pair<_Ty1,_Ty2> &)' : cannot convert parameter 1 from 'E' to 'const std::pair<_Ty1,_Ty2> &' 注释掉的行给出以下错误:错误C2664:'std :: pair <_Ty1,_Ty2> :: pair(const std :: pair <_Ty1,_Ty2>&)':无法将参数1从'E'转换为'const std :: pair <_Ty1,_Ty2>&'
The accepted answer does call A
's default constructor. 接受的答案会调用
A
的默认构造函数。 But it also calls A
's compiler-supplied move constructor. 但是它也调用
A
的编译器提供的move构造函数。 If you would like to call only A
's default constructor, you can do this: 如果您只想调用
A
的默认构造函数,则可以执行以下操作:
testMap.emplace_back(std::piecewise_construct, std::forward_as_tuple(E1),
std::forward_as_tuple());
Or here is a minor re-spelling: 或这里是一个小的重新拼写:
testMap.emplace_back(std::piecewise_construct, std::forward_as_tuple(E1),
std::tuple<>{});
These rewrites are admittedly much uglier than: 这些重写公认比以下丑陋得多:
testMap.emplace_back(E1, A{});
But if saving a call to A(A&&)
is something you want to do, this is how to do it. 但是,如果要保存对
A(A&&)
的呼叫,这就是方法。
Just like you can't construct a std::pair<E, A>
from just E1
, you can't emplace it either. 就像您不能仅从
E1
构造std::pair<E, A>
一样,您也不能放置它。 So just provide a default-constructed A
: 因此,只需提供一个默认构造的
A
:
testMap.emplace_back(E1, A{});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.