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