C++ 继承和模板函数

leJ*_*Jon 6 c++ inheritance templates

我想知道是否有继承模板函数的模式/方法?模板函数不能是虚拟的,因此如果我的基类有模板函数并且我的派生类也有相同的模板函数,则在以下示例中将始终调用基类的函数:

struct Base {
    Base() {}
    template < typename T >
    void do_something(T&  t) const {
        t << "Base" << std::endl ;
    }
    };

struct Foo : Base {
    Foo() : Base () {}
    template < typename T >
    void do_something(T&  t) const {
        t << "Foo" << std::endl ;
    }
};

struct Bar : Foo {
    Bar() : Foo() {}
    template < typename T >
    void do_something(T&  t) const {
        t << "Bar" << std::endl ;
    }
};


int main(int argc, char** argv)
{

    Base *b = new Base() ;
    Base *f = new Foo() ;
    Base *ba = new Bar() ;

    b->do_something(std::cout) ;
    f->do_something(std::cout) ;
    ba->do_something(std::cout) ;

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

所以这个程序总是打印:

Base
Base
Base
Run Code Online (Sandbox Code Playgroud)

有没有办法让我的程序打印:

Base
Foo
Bar
Run Code Online (Sandbox Code Playgroud)

实际上,我发现这样做的唯一方法是制作 static_cast :

...
static_cast<Foo*>(f)->do_something(std::cout) ;
static_cast<Bar*>(ba)->do_something(std::cout) ;
...
Run Code Online (Sandbox Code Playgroud)

是否有任何模式或优雅的方法来封装强制转换,以便在函数调用中不会注意到它?感谢您的回复

asc*_*ler 4

您几乎总是可以通过将功能拆分为更小的部分来完成您需要的操作,必要时使每个部分模板化,或者必要时使每个部分虚拟化。在这个例子中,这很简单:

struct Base {
    Base() {}
    template < typename T >
    void do_something(T&  t) const {
        t << something_piece() << std::endl ;
    }
    virtual const char* something_piece() const {
        return "Base";
    }
};

struct Foo : Base {
    Foo() : Base () {}
    const char* something_piece() const {
        return "Foo";
    }
};

struct Bar : Foo {
    Bar() : Foo() {}
    const char* something_piece() const {
        return "Bar";
    }
};
Run Code Online (Sandbox Code Playgroud)

它可能会变得更复杂,但这个想法在结合编译时和运行时差异方面非常强大。