0

I have this code:

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;
}

And the following error:

struct 'All' has no member named 'value'

And i don't know how to avoid this error. It seems that in the for loop tmp is a All object, and All objects has no member named value. They have no ways to access to child struct (any) member variable from the All object tmp to avoid this problem and have a fully fonctionnal generic vector ?

1 Answers1

0

Since the base / derived class are not polymorphic -> value can't be accessed using base pointer type.

You can add a virtual function to print the 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;
}
vito
  • 473
  • 1
  • 7
  • 17
  • but i don't want to print the value to the standard output. I want to `print()` to return the value of `any::value`. But i can't do it, because this will make a trouble when making the declaration of `any::print()`in `All` because i don't know the return type in the declaration of it. Help me ! – rangerprice Aug 26 '15 at 19:49
  • then delete the base class, and just use "any" class with template type T – vito Aug 27 '15 at 04:07