C++ std::any how to check if type of std::any is vector

1.3k Views Asked by At
#include <iostream>
#include <vector>
#include <string>
#include <any>
#include <map>
#include <functional>
#include <exception>
using namespace std;
using MapAny = std::map<string, any>;

int square(int x) {
    return x*x;
}

vector<int> parse(map<string, vector<MapAny>> mapping)
{
    vector<MapAny> func_square = mapping["square"];
    vector<int> res;
    for (const auto &mapany : func_square) {
        try {
            int x = any_cast<int>(mapany.at("x"));    
            res.push_back(square(x));
        }
        catch (exception e) {
            vector<int> xs = any_cast<vector<int>>(mapany.at("x"));
            for (int x : xs) res.push_back(square(x));
        }        
    }

    return res;
}

int main()
{
    map<string, vector<MapAny>> function_map_value, function_map_array;
    function_map_value = {
        {"square", { {{"x", 5}}, {{"x", 10}} }}
    };
    
    vector<MapAny> vec;    
    vec.push_back({{"x", vector<int>({5, 10}) }});
    function_map_array = {
        {"square", vec}
    };

    vector<int> res1 = parse(function_map_value);
    vector<int> res2 = parse(function_map_array);
    for (int i=0; i<res1.size(); i++) cout << res1[i] << " "; cout << "\n";
    for (int i=0; i<res2.size(); i++) cout << res2[i] << " "; cout << "\n";
    return 0;
}

I'm trying to make a function parser that can accept any type, such as both scalar and vector values, like in Python dict().

However, I'm not sure how to check if a std::any object has type std::vector. In the code above, if any_cast fails, it will throw exception and I know it's a std::vector. It's ugly and rely on throwing exception as an expected behavior.

How can I change the above code into something like:

if (is_vector(mapany.at("x")) {
  // deal with vector
}
else {
  // deal with scalar
}
0

There are 0 best solutions below