Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::get<T> for `variant` a global function?

Can anyone tell me why std::get<T> of C++17 is a global function and not a member-function of variant<...>?

like image 577
Bonita Montero Avatar asked Feb 05 '17 20:02

Bonita Montero


People also ask

What is the point of std :: variant?

Its purpose is to demonstrate that std::variant can use one of the variant type's converting constructors as long as it is unambiguous. std::variant<std::string, int> x("abc"); instead, to show that off more clearly.

What is std :: variant in C++?

The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value (this state is hard to achieve, see valueless_by_exception).

How does C++ variant work?

It holds one of several alternatives in a type-safe way. No extra memory allocation is needed. The variant needs the size of the max of the sizes of the alternatives, plus some little extra space for knowing the currently active value. By default, it initializes with the default value of the first alternative.


1 Answers

If get<T>() were a member function template, a template keyword would be needed when it is called in a dependent context. For example:

template <typename Variant>
void f(Variant const& v) {
    auto x0 = v.template get<T>(); // if it were a member
    auto x1 = get<T>(v);           // using a non-member function
}

Even without a using declaration or directive get() is found as both std::variant<...> and get() are declared in namespace std. Thus, there seems to be no good reason to make it a member function as the global function is easier to use.

like image 65
Dietmar Kühl Avatar answered Oct 05 '22 12:10

Dietmar Kühl