通过模板专门化继承

cra*_*esh 4 c++ inheritance templates

最近我发现了一个更容易进行模板特化而不是真正继承的情况.派生类只需实现一个纯虚函数,并且没有自己的成员.它是这样的:

#include <iostream>

class Interface {
public:
    virtual void calculate() = 0;
    virtual float getResult() = 0;
};

class Base : public Interface {
    float result;
public:
    Base() : result(1) {};
    virtual ~Base() {};

    virtual void calculate();
    virtual float getValue() = 0; // do some very complex calculation here

    float getResult() { return result; }
};

class DerivedA : public Base {
public:
    DerivedA() : Base() {};
    ~DerivedA() {};

    float getValue();
};

class DerivedB : public Base {
public:
    DerivedB() : Base() {};
    ~DerivedB() {};

    float getValue();
};

void Base::calculate() {
    for (int i = 0; i < 10; i++)
        result += getValue();
}

float DerivedA::getValue() {
    return 1;
}

float DerivedB::getValue() {
    return 1.1;
}

int main() {
    Interface * a = new DerivedA();
    a->calculate();

    Interface * b = new DerivedB();
    b->calculate();

    std::cout << "Result A: " << a->getResult() << std::endl;
    std::cout << "Result B: " << b->getResult() << std::endl;

    delete a;
    delete b;
}
Run Code Online (Sandbox Code Playgroud)

这可以写成专门的模板:

#include <iostream>

class Interface {
public:
    virtual void calculate() = 0;
    virtual float getResult() = 0;
};

template<typename T>
class Base : public Interface {
    float result;
public:
    Base() : result(1) {};

    void calculate();
    float getValue(); // do some very complex calculation here

    float getResult() { return result; };
};

typedef Base<int>   DerivedA; // actually int and float are only examples
typedef Base<float> DerivedB; // and may be some much more complex types!

template<typename T>
void Base<T>::calculate() {
    for (int i = 0; i < 10; i++)
        result += getValue();
}

template<typename T>
float Base<T>::getValue() {
    return 0;
}

template<>
float Base<int>::getValue() {
    return 1;
}

template<>
float Base<float>::getValue() {
    return 1.1;
}

int main() {
    Interface * a = new DerivedA();
    a->calculate();

    Interface * b = new DerivedB();
    b->calculate();

    std::cout << "Result A: " << a->getResult() << std::endl;
    std::cout << "Result B: " << b->getResult() << std::endl;

    delete a;
    delete b;
}
Run Code Online (Sandbox Code Playgroud)

两个示例都给出了相同的结果,我猜第二个示例更快,因为不需要计算虚拟表(方法getValue()甚至可以在第二种情况下内联).

所以我的问题是:使用模板专业化而不是继承有什么限制?有没有我没见过的副作用?继承优于模板专业化的任何好处?我知道我不能为专门的类创建新的成员和方法,因为我可以为派生做.但对于这种用例,我只需要实现一些特定于类型的代码,这是一种通用的,更高效的方法吗?

顺便问一下:这个模式有名字吗?

qua*_*dev 6

模板和继承不可互换.

  • 模板表示静态多态(即编译时的多态)

  • 继承允许运行时多态:您可以操作Base类指针并期望运行时为您调用正确的虚函数.

使用模板方法,如果你想操纵一个Base<>对象容器(例如std::vector<Base<??>>)并调用calculate()它们,该怎么办?你不能.

因此,尽管继承和模板都表达了接口和多态,但它们实际上是不同的动物:选择一个而不是依赖于您的上下文,以及如何使用类型.

注意:

性能考虑因素不应改变此选择