【发布时间】:2016-12-11 23:11:34
【问题描述】:
如果我使用 explicit 构造函数创建结构
struct A {
int x;
explicit A(int x):x(x){};
};
然后将它用作std::map 中的mapped_type,我就可以使用分段构造函数来代替:
#include <map>
std::map<int, A> foo;
foo.emplace(
std::piecewise_construct,
std::forward_as_tuple(1),
std::forward_as_tuple(10)
);
但是当我尝试使用移动或模板构造函数时,我得到错误并且无法编译:
foo.emplace(std::make_pair(2, 20)); // <-- doesn't work
foo.emplace(3, 30); // <-- doesn't work
这里发生了什么?直到现在,我还没有意识到这些不同的用法之间存在很大差异。我想,使用 pair move 构造函数,从std::pair<int, A>... 进行隐式转换可能是有意义的,但为什么必须在模板构造函数中发生这种情况?那么为什么不使用分段构造函数呢??
我查了一下,但 std::map::emplace 和 explicit 的文档并没有真正为我澄清这一点。
【问题讨论】:
-
编译器/版本?
-
gcc 版本 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)
标签: c++ c++11 constructor