【问题标题】:generic programming with polymorphism and generic vector具有多态性和泛型向量的泛型编程
【发布时间】:2015-08-26 03:28:44
【问题描述】:

我有这个代码:

struct All { public: All() {} ~All() {} };

template <typename T>
struct any : public All
{
    public:
        any() : All() {}
        ~any() {} 
        T value;
};

int main()
{
    any<int>* a = new any<int>;
    a->value = 55;

    any<string>* b = new any<string>;
    b->value = "Hello World !";

    vector<All*> vec;
    vec.push_back(a);
    vec.push_back(b);

    for (int i = 0; i < (int)vec.size(); i++) {
        All* tmp = vec[i];
        cout << tmp->value << endl; // Error appears here
    }

    return 0;
}

还有以下错误:

struct 'All' 没有名为 'value' 的成员

而且我不知道如何避免这个错误。似乎在 for 循环中tmp 是一个 All 对象,并且 All 对象没有名为 value 的成员。 他们无法从 All 对象 tmp 访问子结构 (any) 成员变量来避免这个问题并拥有一个功能齐全的通用向量?

【问题讨论】:

  • 你可以给Allany&lt;T&gt;添加一个print虚函数,然后调用它。

标签: c++ templates vector polymorphism generic-programming


【解决方案1】:

由于基类/派生类不是多态的-&gt; value 不能使用基指针类型访问。

您可以添加一个虚函数来打印该值。

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

struct All
{
public: All() {} ~All() {}
        virtual void print() = 0;
};

template <typename T>
struct any : public All
{
public:
    any() : All() {}
    ~any() {}
    T value;

    virtual void print() override
    {
        cout << value << endl;
    }
};

int main()
{
        auto a = std::make_shared<any<int>>();
a->value = 55;

auto b = std::make_shared<any<string>>();
b->value = "Hello World !";

vector<std::shared_ptr<All>> vec;
vec.push_back(a);
vec.push_back(b);

for (auto const& elem : vec)
{
    elem->print();
}
    return 0;
}

【讨论】:

  • 但我不想将值打印到标准输出。我想print() 返回any::value 的值。但是我做不到,因为在All 中声明any::print() 时会很麻烦,因为我不知道它声明中的返回类型。帮帮我!
  • 然后删除基类,只使用模板类型为T的“any”类
猜你喜欢
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 2022-08-14
  • 2014-06-01
  • 1970-01-01
相关资源
最近更新 更多