4

矢量正常工作

Header
std::vector<std::shared_ptr<SceneNode>> subnodes_m;

Definition
void CompositeSceneNode::AddChild(SceneNode* subnode_p)
{
    subnodes_m.emplace_back(subnode_p);
}

多图没有

Header
std::multimap<unsigned int, std::shared_ptr<SceneNode>> subnodes_m;

Definition
void CompositeSceneNode::AddChild(SceneNode* subnode_p, unsigned int layerIndex)
{
    subnodes_m.emplace(layerIndex, subnode_p);
}

我收到以下错误:

error C2664: 'std::pair<_Ty1,_Ty2>::pair(const unsigned int &,const _Ty2 &)' :
cannot convert parameter 2 from 'RendererD3DWrapper::SceneNode *'
to 'const std::shared_ptr<_Ty> &'   

有人有线索吗?

4

1 回答 1

11

如果没有into和into的隐式转换,则不能构造 a std::pair<T1,T2>with arguments 类型。在您的情况下, into没有隐式转换。UVUT1VT2SceneNode*std::shared_ptr<SceneNode>

从 C++ 标准:

§ 20.3.2 类模板pair [pairs.pair]

template<class U, class V> constexpr pair(U&& x, V&& y);
  1. 要求: is_constructible<first_type, U&&>::valuetrueis_constructible<second_type, V&&>::valuetrue

  2. 效果:构造函数firststd::forward<U>(x)和初始化secondstd::forward<V>(y)

  3. 备注:如果U不能隐式转换为first_typeV不能隐式转换second_type为此构造函数,则不应参与重载决议

话虽如此,您不能std::pair<T1,T2>像下面那样初始化一个(作为就地emplace构建一个已知的):std::pair<key_type, mapped_type>value_typestd::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::vectorof std::shared_ptr's 一起工作呢?

std::vector<std::shared_ptr<T>>::emplace_back成员函数将 的参数转发给emplace_back的构造函数std::shared_ptr<T>,满足明确的上下文要求。在 amap和 a的情况下,如果这些元素的参数类型和参数类型之间的转换不是隐式的(如上所述),则嵌入的multimap类型是 a ,它具有将参数进一步转发到其元素中的构造函数。pair

于 2014-09-23T10:54:59.583 回答