c++ - 如何用具体类之一实例化抽象类?

标签 c++ templates inheritance polymorphism wrapper

我想知道以下段落的含义以及如何实现它。我昨天问了一个与同一问题相关的问题here .在昨天的问题中,我被告知这是不可能的,但我认为下面的段落表明这是可能的?

Your methods use specific exponentiation methods. However, the exponentiation classes are subclasses of a general abstract exponentiation class. You could implement these to use this abstract class, and just instantiate that with one of the concrete classes. This would give you the flexibility to experiment with and/or change exactly what exponentiation algorithms are used, for example, if someone identifies something better in the future....

本质上,我有一堆按以下方式组织的求幂技术-

template <class T>
class Exponentiation
{
    public:
    Exponentiation() {};
    virtual ~Exponentiation() {};

    // computes C = A^n
    virtual void power(T& C, const T& A, const int n) = 0;
}

template <class T>
class ExpA : public Exponentiation<T>
{
    public:
    ExpA() {};
    ~ExpA() {};

    void power (T& C, const T& A, const int n);
}

template <class T>
class ExpB : public Exponentiation<T>
{
    protected:
    var1;
    var2;

    public:
    ExpB() {};
    ~ExpB() {};

    func1();
    func2();
    void power (T& C, const T& A, const int n);
}

现在,最初我有一个 performExp() 调用特定的求幂方法,例如 -

performExp()
{
    ExpA<long> objA;
    objA.power();

    // or

    ExpB<long> objB;
    objB.func1();
    objB.func2();
    obj.power ()
}

但据我所知,更好的选择是在 performExp() 中使用基类,然后在 main() 中使用一个实例化基类具体类 ExpAExpB

如何做这件事?阅读昨天的答案后,我的一个想法是使用某种包装器,但我很难想象它。

最佳答案

我不明白你到底想达到什么目的。但第一个问题是你是否需要运行时多态性或编译时多态性。看你的代码,我猜是后者。

因此,对于这个答案,我假设您拥有模板化的求幂类,并且您最终编写了 compelx 计算程序,这些程序将确切地知道它们是在 ExpA 还是在 上工作ExpB.

然后我建议将 performExp() 实现为模板函数,以通用方式指示如何执行操作:

template <class T, template <class U> class Exp>
void performExp(Exp<T>& obj)
{
     obj.power();
}

然后可以为此模板提供特化或部分特化:

template <class T>
void performExp(ExpB<T>& obj)
{
     obj.func1();
     obj.func2(); 
     obj.power();
}

当您随后在代码中使用这些模板时,编译器将推导参数并使用可能存在的任何特化:

int main() {
    ExpA<long> a;
    performExp(a);

    ExpB<long> b; 
    performExp(b);       //specialized form will be used
}

你可以在这个online demo中测试结果

关于c++ - 如何用具体类之一实例化抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51933767/

相关文章:

c++ - Qt:将拖放委托(delegate)给 child 的最佳方式

c++ - 为什么这个 OpenGL-es 纹理绑定(bind)到 cocos2d 2.0 中的山丘?

C++17 模板推导指南不用于空参数集?

javascript - 模板破坏了 meteor 包

c++ - 无法将 loadFinished SIGNAL 连接到自定义 SLOT

c++ - 等待事件循环为空/等到 Qt5 小部件关闭

c++ - 带有 enable_if 和重载的 SFINAE

c++ - 奇怪的重复模板模式 : double inheritance

使用工厂的 C++ 接口(interface)继承

javascript - 尝试了解 JavaScript 中的继承——这里发生了什么?