Can anyone tell me why std::get<T>
of C++17 is a global function and not a member-function of 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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With