0

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?

Dennix
  • 115
  • 1
  • 10
  • 2
    The term "aggregate" have a very special meaning in C++, and not every container or structure is an aggregate. For example `std::array<...>` is an aggregate, but `std::vector<...>` is not. See the definitions of an aggregate [here](https://en.cppreference.com/w/cpp/language/aggregate_initialization#Definitions). – Some programmer dude Feb 02 '23 at 13:52
  • 8
    `std::vector` is not a type. It's a type template. If you use an actual type it works. And if you find the repetition of the type convoluted (with which I and others agree!) you don't have to do that: just use `auto` to declare the variables. – Konrad Rudolph Feb 02 '23 at 13:52

1 Answers1

1

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"]);
farnz
  • 70
  • 6