std::any_cast to get an unnamed enum?

Viewed 68

I have queue of std::anys which I’m populating variadically before I know any of the types, and I’m trying to cast any unnamed enums which were passed to just be ints while populating it.

Suppose I have the following code:

enum {
    VALUE_1,
    VALUE_2,
};

enum {
    VALUE_3
};

template<typename ...T>
std::queue<std::any> extract_variadic_to_queue_impl(const T&... args) {
    std::vector<std::any> vec = { args ... };
    std::queue<std::any> ret;
    for (unsigned int i = 0, max = vec.size(); i < max; i++) {
        std::string type_name = vec[i].type().name();
        if (type_name.starts_with("enum <unnamed-enum>")) {
            ret.push((int)std::any_cast<???>(vec[i]));
        }
        else {
            ret.push(vec[i]);
        }
    }
    return ret;
}

template<typename ...T>
std::queue<std::any> extract_variadic_to_queue(T... args) {
     return extract_variadic_to_queue_impl(std::any(args)...);
}

#define EXTRACT(var_name, type) type var_name = std::any_cast<type>(q.front()); q.pop();

void test() {
    std::queue<std::any> q = extract_variadic_to_queue(
        0, 
        "hi", 
        VALUE_2, 
        2.0f, 
        2.0
    );
    EXTRACT(my_int, int);
    EXTRACT(my_string, const char*);
    EXTRACT(my_constant, int);
    EXTRACT(my_float, float);
    EXTRACT(my_double, double);
}

I know that for all unnamed enums, type_name will evaluate to “enum <unnamed-enum>-“ followed by the name of the first value (in this case, “enum <unnamed-enum>-VALUE_1”). Assuming I can’t just name the enum, what would I need to replace ??? with in order to make this work? I know it isn’t an int because EXTRACT(my_constant, int); throws bad_any_cast if I don’t check for unnamed enums in extract_variadic_to_queue_impl, but I assume there has to be some way to get the value, otherwise it wouldn’t let me store it at all, right?

Furthermore, does anything change if test() is changed to:


void test() {
    std::queue<std::any> q = extract_variadic_to_queue(
        0,
        "hi", 
        VALUE_2, 
        2.0f, 
        2.0, 
        VALUE_3 //now passes values from two different enums
    );
    EXTRACT(my_int, int);
    EXTRACT(my_string, const char*);
    EXTRACT(my_constant, int);
    EXTRACT(my_float, float);
    EXTRACT(my_double, double);
    EXTRACT(my_other_constant, int);

}

Thanks!

1 Answers

You are not supposed to use type().name() to make such decisions at all, not for unnamed enums or any other type. The names are completely implementation-defined. There is no guarantee what they will be (or that they will be unique).

You should check the contained type with std::any_cast instead or by ==-comparing type() to typeid(/*type here*/).

To retrieve a stored type you must have an alias for that type one way or another. Either you give the enum a name or you obtain the type via decltype from its enumerator (or a variable of its type).

Related