【发布时间】:2016-10-08 17:07:33
【问题描述】:
我在尝试从std::shared_ptr<void>“复制”到模板化std::shared_ptr<T> 时遇到了这个问题。它看起来像这样:
template < >
class TDynamic< void >
{
protected:
std::shared_ptr< void > m_pointer;
public:
// Here i got constructors, functions etc
template < typename U >
TDynamic< U > SwitchType()
{
TDynamic< U > returnValue;
returnValue.m_pointer = std::shared_ptr< U >(m_pointer); // error here
}
};
错误是这样说的:
c:\...path_here...\tdynamic.hpp(426): error C2440: 'type cast': cannot convert from 'const std::shared_ptr< void >' to 'std::shared_ptr< T >'
1> with
1> [
1> T=grim::Actor
1> ]
1> c:\...path_here...\tdynamic.hpp(426): note: No constructor could take the source type, or constructor overload resolution was ambiguous
编译器和 IDE:Visual Studio 2015 社区
对于这种情况,这对我来说是必要的。假设我有类“Actor”和派生类“APlayer”
class Actor
{
public:
};
class APlayer
: public Actor
{
public:
};
int main()
{ // some code here
TDynamic< APlayer > test1(new APlayer);
TDynamic< void > test2(test1);
TDynamic< Actor > test3(test2); // error here
}
我可以将整个代码粘贴到这里,但它大概有 550 行,而且大部分都无关紧要。我只需要复制那个std::shared_ptr。
【问题讨论】:
-
查看
static_pointer_cast,但要非常小心。 -
“我可以在这里粘贴整个代码,但它大概有 550 行,而且大部分都没有关系” 了解如何构造 minimal reproducible example。
标签: c++ casting stl initialization shared-ptr