简体   繁体   English

继承和模板函数 C++

[英]Inheritance and template function c++

I was wondering if there are pattern/ways to inherit template functions ?我想知道是否有继承模板函数的模式/方法? Template functions can not be virtual so if my base class has a template function and my derived class has the same, the function of the base class will always be called in the following example :模板函数不能是虚拟的,所以如果我的基类有一个模板函数并且我的派生类有相同的模板函数,那么在下面的例子中总是会调用基类的函数:

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 ;
}

So this program always print :所以这个程序总是打印:

Base
Base
Base

Is there a way to make my program print :有没有办法让我的程序打印:

Base
Foo
Bar

Actually the only way I found for doing that is to make a static_cast :实际上,我发现这样做的唯一方法是制作一个 static_cast :

...
static_cast<Foo*>(f)->do_something(std::cout) ;
static_cast<Bar*>(ba)->do_something(std::cout) ;
...

Is there any pattern or elegant way to encapsulate the cast so that it will be unnoticeable from the function call ?是否有任何模式或优雅的方式来封装强制转换,以便它不会从函数调用中引起注意? Thanks for your replies感谢您的回复

You can almost always do what you need by splitting the function into smaller parts, making each part templated if necessary, or virtual if necessary.您几乎总是可以通过将功能拆分为更小的部分、根据需要对每个部分进行模板化或在必要时进行虚拟化来完成您需要的操作。 In this example, that's as simple as:在这个例子中,这很简单:

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";
    }
};

It can get more complicated than that, but the idea is pretty powerful at combining compile-time and run-time differences.它可能比这更复杂,但这个想法在结合编译时和运行时差异方面非常强大。

Do you have the option to change the struct to a Template class rather than template methods?您是否可以选择将结构更改为模板类而不是模板方法?

If so:如果是这样的话:

Template<typename T>
struct Base
{
public:
    virtual void doSomething();
 };


Template<typename T>
struct Foo : Base<T>
{
public:
    virtual void doSomething();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM