C++ Generic Vector

2019-04-09 17:03发布

问题:

Is it possible in c++ to create a vector of multiple types? I'd like to be able to build and iterate over a vector that contains many different types. For example:

vector<generic> myVec;
myVec.push_back(myInt);
myVec.push_back(myString);
etc...

The vector needs to be able to hold differing data types. Is there another vector-like type I should be using in the c++ library?

Any direction is appreciated.

回答1:

You could use boost::any. For instance:

#include <vector>
#include <boost/any.hpp>
#include <iostream>

struct my_class { my_class(int i) : x{i} { } int x; };

int main()
{
    std::vector<boost::any> v;

    v.push_back(42);
    v.push_back(std::string{"Hello!"});
    v.push_back(my_class{1729});

    my_class obj = boost::any_cast<my_class>(v[2]);
    std::cout << obj.x;
}

If you want to restrict the set of allowed types to some defined range, you could use boost::variant instead:

#include <vector>
#include <boost/variant.hpp>
#include <iostream>

struct my_class { my_class(int i) : x{i} { } int x; };

int main()
{
    typedef boost::variant<int, std::string, my_class> my_variant;
    std::vector<my_variant> v;

    v.push_back(42);
    v.push_back("Hello!");
    v.push_back(my_class{1729});

    my_class obj = boost::get<my_class>(v[2]);
    std::cout << obj.x;
}

boost::variant also supports visiting. You could define a visitor that can handle all the possible types in the variant:

struct my_visitor : boost::static_visitor<void>
{
    void operator () (int i)
    {
        std::cout << "Look, I got an int! " << i << std::endl;
    }

    void operator () (std::string const& s)
    {
        std::cout << "Look, I got an string! " << s << std::endl;
    }

    void operator () (my_class const& obj)
    {
        std::cout << "Look, I got a UDT! And inside it a " << obj.x << std::endl;
    }
};

And then invoke it as done below:

int main()
{
    typedef boost::variant<int, std::string, my_class> my_variant;
    std::vector<my_variant> v;

    v.push_back(42);
    v.push_back("Hello!");
    v.push_back(my_class{1729});

    my_visitor mv;
    for (auto const& e : v)
    {
        e.apply_visitor(mv);
    }
}

Here is a live example. The nice thing about boost::variant is that it will perform a compile-time check to make sure that your visitor can handle all the types that the variant can hold.