几个星期以来,我一直在互联网上搜索有关 c++ 中的异构列表 ( vector
, array
, list
),但是,在所有站点和论坛中,答案都是相同的:boost::any
,但我想要一种在纯 C ++ 中执行此操作的方法。我开发了这个:
#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); //float
vec.insert("txt"); //string
for (int i = 0; i < vec.size(); i++)
{
cout << vec.at(i);
}
return 0;
}
但我得到这个错误:
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);
~~~~~^~~~~~~~~~~~
我知道问题在于在类中或类中auto
用作返回类型,但我不知道如何解决。auto get()
any
auto& at(int idx)
queue