我试图&#34;复制&#34;从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
编译器&amp; IDE:Visual Studio 2015社区
对于这种情况,这对我来说是必要的。让我们说我有班级&#34;演员&#34;和派生类&#34; APlayer&#34;
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
。
答案 0 :(得分:1)
您可以使用static_pointer_cast
:
returnValue.m_pointer = static_pointer_cast<U>(m_pointer);
由您来保证此演员表是合法的(它被定义为与static_cast<U*>(m_pointer.get())
一样合法)。