我希望将任何类型的矢量存储在另一个矢量中。所以,例如我有两个矢量实例," std :: vector v1"和" std :: vector v2"。我想把它们放到一个载体中。我已经尝试过这样:
std::vector<int> v1;
std::vector<std::string> v2;
std::vector< std::vector<boost::any> > vc;
vc.push_back(v1);
以及其他几种方式,但没有任何作用。你知道一个可能的解决方案吗?
谢谢!
答案 0 :(得分:2)
免责声明:我不建议这样做。
但如果你坚持,这就是这种可憎的开始:
#include <vector>
#include <memory>
#include <functional>
#include <boost/any.hpp>
class any_vector
{
using any = boost::any;
struct concept
{
virtual any at(std::size_t) = 0;
virtual any at(std::size_t) const = 0;
virtual ~concept() = default;
};
template<class T>
struct model : concept
{
model(std::vector<T> v) : _data(std::move(v)) {}
virtual any at(std::size_t i) override { return boost::any(std::ref(_data.at(i))); }
virtual any at(std::size_t i) const override { return boost::any(std::cref(_data.at(i))); }
std::vector<T> _data;
};
concept& deref() { return *vec_; }
concept const& deref() const { return *vec_; }
std::unique_ptr<concept> vec_;
public:
boost::any at(std::size_t i) const { return deref().at(i); }
boost::any at(std::size_t i) { return deref().at(i); }
template<class T>
any_vector(std::vector<T> v)
: vec_(std::make_unique<model<T>>(std::move(v)))
{}
};
int main()
{
any_vector a(std::vector<int> { 1, 2, 3 });
any_vector b(std::vector<double> { 1.1, 2.2, 3.3 });
std::vector<any_vector> va;
va.push_back(std::move(a));
va.push_back(std::move(b));
auto anything = va.at(0).at(1);
// how you deal with the resulting `any` is up to you!
}
注意any_vector :: at(x)将返回一个boost :: any,它将包含一个const-ref或一个对象的ref。
编写有用的代码来推断出事物是什么并使用它将是一个挑战......