[英]C++: How to create a vector storing vectors of any type?
我想將任何類型的向量存儲在另一個向量中。 因此,例如,我有兩個向量實例,“ 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);
和其他幾種方式,但沒有任何效果。 您知道可能的解決方案嗎?
謝謝!
免責聲明:我不建議這樣做。
但是,如果您堅持認為,這是可憎的開始:
#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或對某個對象的引用。
編寫有用的代碼來推斷事物的本質並加以使用將是一個挑戰...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.