Binh Van Pham
Binh Van Pham

Reputation: 123

Getting back original type of boost variant variable

Would you please help me getting back the typename of the original object put into a boost::variant?

I have something like this

typedef boost::variant<macro,module> ref_var;

Is it possible to get back the typename of the original object? In this case (macro or module)

I was trying to get it using

typeid(v).name()

but it gives me weird name that is neither macro nor module:

PN5boost7variantI5macro6moduleNS_6detail7variant5void_ES5_S5_S5_S5_S5_S5_S5_S5_S5_S5_S5_S5_S5_S5_S5_S5_S5_EE

Would you please help?

Upvotes: 0

Views: 741

Answers (3)

Ferruccio
Ferruccio

Reputation: 100658

If all you need is to get back the textual representation of the types held in a variant, you can roll your own solution:

const char* ref_var_typename(const ref_var& v) {
    static const char* types[] = { "macro", "module" };
    return types[v.which()];
}

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 473447

There is no way (in the standard) to get the actual C++ typename of any type, whether from a variant or not. The best you can do is get the type_info, but as you see, that is the mangled name, not the actual C++ typename.

Upvotes: 0

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

variant::type() returns std::type_info for the contents of the variant. Just don't use this to choose how to act on the variant — this is best done with visitors.

Upvotes: 3

Related Questions