向下转型 unique_ptr 以访问函数

5 c++ downcast static-cast unique-ptr

如何让它发挥作用?之前的错误/注释行return 0;

#include <iostream> 
#include <vector>
#include <memory>

using namespace std;


class Base 
{
    public:   
        void foobar() { cout << "foobar"; }
};

class Derived : public Base
{
    public:

        void print() { cout << "hello world!"; }
};

int main(int argc, char *argv[]) 
{
    vector<unique_ptr<Base>> bases;
    bases.push_back(unique_ptr<Base> (new Derived()));

    //ok
    bases[0]->foobar();
    //error
    //how can I make this works?
    static_cast<Derived*> (bases[0])->print();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

imr*_*eal 3

要执行此转换,您需要像这样获取实际存储的指针base[0]

static_cast<Derived*>(bases[0].get())->print()
Run Code Online (Sandbox Code Playgroud)

编辑:

我同意@Tietbohl 的观点,因为这样dynamic_cast更安全,而且向下转型可能是糟糕设计的一个指标。然而,在某些情况下,向下转型是有意义的,并且您可以确定它是安全的。

例如,假设您有一个工厂方法,它创建一个具有特定接口的对象,但您提供了一个参数来指示您想要一个特定的具体类,然后您需要对返回的对象执行操作:

Interface* object = factory->CreateObject([parameter specifies type ConcreteA]);

...
static_cast<ConcreteA*>(object)->FuncOnA();
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以通过简单地使用 来避免 RTTI 的复杂性static_cast

  • @Danvil 如果您确定指针可以向下转型,则不必如此。我不喜欢“dynamic_cast”,因为它增加了启用 RTTI 的需要。无论如何,应该尽可能避免沮丧。 (3认同)