Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;将派生类shared_ptr传递给模板化函数_C++_Templates_Inheritance_Boost_Shared Ptr - Fatal编程技术网

C++ C++;将派生类shared_ptr传递给模板化函数

C++ C++;将派生类shared_ptr传递给模板化函数,c++,templates,inheritance,boost,shared-ptr,C++,Templates,Inheritance,Boost,Shared Ptr,首先是一些应该有效的东西,然后是一些不起作用的东西。为什么不呢?这是个问题 我宣布两类: class Base { ... }; class Derived : public Base { ... }; 然后,我在其他地方具有以下功能: void foo(shared_ptr<Base> base); void foo(共享的ptr基); 下面的代码应该正常工作吗 share_ptr<Derived> derived; foo(derived); share

首先是一些应该有效的东西,然后是一些不起作用的东西。为什么不呢?这是个问题

我宣布两类:

class Base { ... };
class Derived : public Base { ... };
然后,我在其他地方具有以下功能:

void foo(shared_ptr<Base> base);   
void foo(共享的ptr基);
下面的代码应该正常工作吗

share_ptr<Derived> derived;
foo(derived);
share\u ptr派生;
foo(派生);
现在,忘记上面的内容,我声明三个类:

class Foo { ... };
template <typename TYPE> class Base { ... };
class Derived : public Base<Foo> { ... };
class Foo{…};
模板类基类{…};
派生类:公共基{…};
在其他地方,我声明了一个模板函数:

template <typename TYPE> void foo(shared_ptr<Base<TYPE> > base); 
模板void foo(共享的ptr基);
以下代码不起作用:

shared_ptr<Derived> derived;
foo(derived);
shared_ptr派生;
foo(派生);
它表示没有找到接受
share\u ptr


首先,原始示例是否有效?第二,在第二个例子中,你认为会是什么问题呢?在这个例子中,我有一个
共享的ptr
给一个从专用基类派生的类。

我不认为编译器会以这种方式经历一个间接层次。相反,您可以显式地实例化类型设置为foo的foo。例如,以下代码通过g++编译:

#include<boost/shared_ptr.hpp>

class Foo {};
template <typename T> class Base {};
class Derived : public Base<Foo> {};

template<typename T>
int foo(boost::shared_ptr<Base<T> > base) {return 0;}

boost::shared_ptr<Derived> derived;
int t = foo<Foo>(derived);

int main() {return 0;}
#包括
类Foo{};
模板类基类{};
派生类:公共基{};
模板
int foo(boost::shared_ptr base){return 0;}
boost::共享的ptr派生;
int t=foo(派生);
int main(){return 0;}

这可能是一个复制粘贴错误,但为了涵盖所有基础,您错过了
共享的“shared”中的“d”\u ptr

,这非常有趣。只需将
添加到
foo
函数的调用中,即可使其正常工作。