如何在一个容器中收集不同类型的对象(来自一个类模板)?

时间:2018-03-15 10:52:36

标签: c++ templates inheritance

我正在尝试像C ++中的代码一样:

我希望将所有对象(从类模板的's'创建)收集到一个容器中,比如std :: vector。我可以通过代码中显示的方式实现它。

我的问题是,如果我想在类f中传递特定类型'T'的参数或通过统一的api传递参数,或者从一个api获取'T'。如何实现?

非常感谢!

#include <iostream>
#include <vector>
#include <string>

class f

{
public:
    f() {}
    virtual ~f() {}

    virtual void p() { std::cout << " class f\n";}
};

template<typename T>
class s : public f
{
public:
    s(T x) { m = x; }
    ~s() {}

    void p() { std::cout << " -> " << x << "\n"; }                                                                                                            
private:
    T m;
};

int main()
{
    int aa = 1;
    float bb = 5.9;
    std::string cc = "abc";

    s<decltype(aa)>* A = new s<decltype(aa)>(aa);
    s<decltype(bb)>* B = new s<decltype(bb)>(bb);
    s<decltype(cc)>* C = new s<decltype(cc)>(cc);

    std::vector<f*> vv;
    vv.push_back(A);
    vv.push_back(B);
    vv.push_back(C);

    for(auto a : vv) {
        a->p();
    }

    return 0;
}  

0 个答案:

没有答案