c++c++17stdvectorstdanyanycast

Is it possible to store and retrieve a container (e.g. std::vector) in an std::any variable?


I would like to have heterogenous map in C++ for my unit test values. Other threads recommended the use of std::any with any_cast for this purpose. This works well for primitive types like int and double but I fail to retrieve the value if I use a std::vector.

My code looks like this:

    std::map<std::string, std::any> expected = {
        { "getInt", 1 },
        { "getDouble", 1.0 },
        { "getVector", std::vector<int> { 1, 2 } },
    }
    
    int getInt = std::any_cast<int>(expected["getInt"])
    double getDouble= std::any_cast<double>(expected["getDouble"])

So far the code works as expected, even though the need for any_cast feels convoluted coming from newer languages. But if I try to do the same for a vector it fails:

    std::vector<int> getVector= std::any_cast<std::vector>(expected["getVector"])

Is there a way to retrieve an aggregate from a std::any value?


Solution

  • You have to include the type of the vector in the std::any_cast. Code:

    std::vector<int> getVector = std::any_cast<std::vector<int>>(expected["getVector"]);