如果没有into和into的隐式转换,则不能构造 a std::pair<T1,T2>
with arguments 类型。在您的情况下, into没有隐式转换。U
V
U
T1
V
T2
SceneNode*
std::shared_ptr<SceneNode>
从 C++ 标准:
§ 20.3.2 类模板pair
[pairs.pair]
template<class U, class V> constexpr pair(U&& x, V&& y);
要求: is_constructible<first_type, U&&>::value
是true
和is_constructible<second_type, V&&>::value
是true
。
效果:构造函数first
用std::forward<U>(x)
和初始化second
。std::forward<V>(y)
备注:如果U
不能隐式转换为first_type
或V
不能隐式转换second_type
为此构造函数,则不应参与重载决议。
话虽如此,您不能std::pair<T1,T2>
像下面那样初始化一个(作为就地emplace
构建一个已知的):std::pair<key_type, mapped_type>
value_type
std::multimap
std::pair<unsigned int, std::shared_ptr<SceneNode>> p( 1, new SceneNode );
因为std::shared_ptr<T>
采用原始指针的构造函数(如下声明)是explicit
构造函数,因此您遇到的错误:
§ 20.9.2.2 类模板shared_ptr
[util.smartptr.shared]
[...]
template<class Y> explicit shared_ptr(Y* p);
在 C++11 中,您应该在std::shared_ptr<T>
调用之前构建一个emplace
:
subnodes_m.emplace(layerIndex, std::shared_ptr<SceneNode>(subnode_p));
,或者您可以使用分段构造将参数转发给对元素的构造函数(而不是将它们转发给std::pair<T1,T2>
自身的构造函数):
subnodes_m.emplace(std::piecewise_construct
, std::forward_as_tuple(layerIndex)
, std::forward_as_tuple(subnode_p));
演示
那么为什么它与std::vector
of std::shared_ptr
's 一起工作呢?
std::vector<std::shared_ptr<T>>::emplace_back
成员函数将 的参数转发给emplace_back
的构造函数std::shared_ptr<T>
,满足明确的上下文要求。在 amap
和 a的情况下,如果这些元素的参数类型和参数类型之间的转换不是隐式的(如上所述),则嵌入的multimap
类型是 a ,它具有将参数进一步转发到其元素中的构造函数。pair