【发布时间】:2020-07-08 16:42:27
【问题描述】:
我有一个类似下面的 C++ 示例,我收到一个指向基类 exampleParent 的指针,并希望将其转换为指向继承类 example 的指针(实际上我只是想调用example) 上的一个函数。需要注意的是继承的类是模板化的。在下面的示例中,我知道模板的类型为int,所以没有问题。一般来说,如果我事先不知道模板的类型,有什么好的方法可以做到这一点?
class exampleParent{};
template<typename P>
class example: public exampleParent
{
public:
int do_something() const
{
std::cout<<"I am doing something"<<std::endl;
return 0;
}
};
boost::shared_ptr<const exampleParent> getPtr()
{
return boost::make_shared<const example<int>>();
}
int main()
{
boost::shared_ptr<const exampleParent> example = getPtr();
auto example_ptr = boost::dynamic_pointer_cast<const example<int>>(example);
return example_ptr-> do_something();
}
我建议的一个解决方案是将代码更改为以下内容:
class exampleParent{};
class something_interface: public exampleParent
{
public:
virtual int do_something() const = 0 ;
};
template<typename P>
class example: public something_interface
{
public:
int do_something() const override
{
std::cout<<"I am doing something"<<std::end;
return 0;
}
};
boost::shared_ptr<const exampleParent> getPtr()
{
return boost::make_shared<const example<int>>();
}
int main()
{
boost::shared_ptr<const exampleParent> example = getPtr();
auto example_ptr = boost::dynamic_cast<const something_interface>(example);
return example_ptr->do_something();
}
这行得通,但感觉有点骇人听闻:something_interface 不应该真的存在,因为它本身没有面向对象的解释。
任何帮助将不胜感激!
【问题讨论】:
-
这实际上是 C++ 中一个非常标准的概念:接口除了为其他人添加他们的实现创建入口点之外什么都不做。
标签: c++ templates inheritance casting