C ++ Heterogeneous list

0

I've been looking for heterogeneous lists in% 1%, vector , array on the internet for weeks on c ++, but on all websites and forums the answer is the same: list , but I wanted a way to do in pure C ++. I developed this:

#include <iostream>
#include <typeinfo>
#include <vector>

using namespace std; 
 //Compiler version g++ 6.3.0

 class any
 {
 public:
    auto get() {}
 };

 template<typename T>
 class anyTyped : public any
 {
 public:
    T val;

    anyTyped(T x)
    {
        val = x;
    }
    T get()
    {
        return val;
    }
 };

 class queue
 {
    vector<any*> x;
    int len = 0;

 public:
    queue()
    {
        x.resize(0);
    }

    template<typename T>
    void insert(T val)
    {
        any* ins = new anyTyped<T>(val);
        x.push_back(ins);
        len++;
    }
    int size()
    {
        return len;
    }

    auto& at(int idx)
    {
        return x[idx]->get();
    }
 };

 int main()
 {

    queue vec;

    vec.insert(5);     //int
    vec.insert(4.3);   //double
    vec.insert("txt"); //char*

    for (int i = 0; i < vec.size(); i++)
    {
        cout << vec.at(i);
    }

    return 0;
 }

But I get the following error:

source_file.cpp: In member function 'auto& queue::at(int)':
source_file.cpp:55:23: error: forming reference to void
    return x[idx]->get();
                       ^
source_file.cpp: In function 'int main()':
source_file.cpp:70:9: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'void')
    cout << vec.at(i);
    ~~~~~^~~~~~~~~~~~

I know that the problem is in using boost::any as a return type, both in% with% in class% with%, and in% with% in class auto , but I do not know how to fix

    
asked by anonymous 18.07.2017 / 20:33

1 answer

1

In this case you could eliminate the get() method and implement operator<< in the any class to play the content of val in std::ostream . This way you do not have to worry about templated (sic) return types, but instead you would only support one type of output stream, in this case.

class any
{
public:
    friend ostream &
    operator<<(ostream &os, const any& a)
    {
        return a.output_to(os);
    }

    virtual ostream &output_to(ostream &os) const = 0;
};

template<typename T>
class anyTyped : public any
{
public:
    T val;

    anyTyped(T x)
    {
        val = x;
    }

    ostream &
    output_to(ostream &os) const
    {
        return os << val;
    }
};

Do not forget to fix the queue::at method to return a reference to the variables of type any :

auto& at(int idx)
{
    return *x[idx];
}

PS: Variables entered in queue ( vec.insert statements in the main() function) are of types double and const char * , not float and string .     

19.07.2017 / 16:10