C++: How to create a vector storing vectors of any type?

后端 未结 1 1310
长情又很酷
长情又很酷 2021-01-17 04:59

I\'d like to store vectors of any type in another vector. So, for example I have two vector instances, \"std::vector v1\" and \"std::vector v2\". And I would like to put the

1条回答
  •  再見小時候
    2021-01-17 05:56

    Disclaimer: I don't recommend this.

    But if you insist, here is the beginnings of such an abomination:

    #include 
    #include 
    #include 
    #include 
    
    
    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
        struct model : concept
        {
          model(std::vector 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 _data;
        };
    
      concept& deref() { return *vec_; }
      concept const& deref() const { return *vec_; }
    
      std::unique_ptr 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
      any_vector(std::vector v)
      : vec_(std::make_unique>(std::move(v)))
      {}
    };
    
    int main()
    {
      any_vector a(std::vector { 1, 2, 3 });
      any_vector b(std::vector { 1.1, 2.2, 3.3 });
    
      std::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!
    }
    

    Note that any_vector::at(x) will return a boost::any which will either contain a const-ref or a ref to some object.

    Writing useful code that deduces what the thing is and uses it is going to be a challenge...

    0 讨论(0)
提交回复
热议问题