c++ - 如何通过多态基类接口(interface)使用模板化子类

标签 c++ templates polymorphism virtual

我有基本的父类和模板化的子类。 我想使用集合中的子级通过父级的多态接口(interface)来枚举它们。 我期望那里有虚拟(多态)函数调用 - 但我只有对 Parent::print() 的静态类型调用

#include <iostream>
#include <vector>
using namespace std;

class Parent {
public:
    Parent() { cout << " parent ctor "; }
    virtual void print() { cout << " Parent::print "; }
};


template <typename T>
class Child : public Parent {
public:
    Child(T value) : var(value) { cout << " child ctor "; }
    virtual void print() { cout << " Child::print " << var; }
protected:
    T var;
};

int main() {
    Child<int> myChild(1);
    Child<double> myDoubleChild(2.);

    vector<Parent> v = {myChild, myDoubleChild};

    for (auto i : v) {
        i.print();
    }

    return 0;
}

实际输出:

 parent ctor  child ctor  parent ctor  child ctor  Parent::print  Parent::print 

预期输出应包含“Child::print”虚拟函数调用

最佳答案

正如 @tchelidze 和 @StenSoft 提到的,有两个缺陷:

  1. 对象切片。蹩脚的错误。 std::vector 使用原始对象
  2. 多态性仅适用于指针或引用

启用动态调度代码应该是这样的:

#include <iostream>
#include <vector>
using namespace std;

class Parent {
public:
    Parent() { cout << " parent ctor "; }
    virtual void print() { cout << " Parent::print "; }
};


template <typename T>
class Child : public Parent {
public:
    Child(T value) : var(value) { cout << " child ctor "; }
    virtual void print() { cout << " Child::print " << var; }
protected:
    T var;
};

int main() {
    Child<int> myChild(1);
    Child<double> myDoubleChild(2.);

//    vector<Parent> v = {myChild, myDoubleChild};
    vector<Parent*> v = {&myChild, &myDoubleChild};

    for (auto i : v) {
//        i.print();
        i->print();
    }
    return 0;
}

这给出了所需的输出:

parent ctor  child ctor  parent ctor  child ctor  Child::print 1 Child::print 2

关于c++ - 如何通过多态基类接口(interface)使用模板化子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34692068/

相关文章:

java - Jakson 多态枚举案例

c++ - 如何让我以前的消息在 Visual Studio 2013 控制台应用程序中消失? (C++)

C++ typedef(来自 MATLAB)

c++ - Windows中的微秒计时器

c++ - 调用模板提供的(静态)函数

c++ - 在 C++ 中覆盖具有不同返回类型的方法

c++ - 执行两次时产生不同结果的相同浮点计算是否表明不符合 IEEE 754?

c++ - 模板常量/非常量方法

templates - 可以在Grails中使用节奏模板引擎吗?

c++ - 当 C++ 中没有多态时如何传递像多态这样的结构