Can anyone tell me why std::get<T>
of C++17 is a global function and not a member-function of variant<...>
?
-
9I'll ask the complementary question: why should it be a member function?– Pete BeckerFeb 5, 2017 at 20:53
-
8Same as for tuple most certainly. The syntax gets too ugly.– Baum mit Augen ♦Feb 5, 2017 at 20:53
-
@PeteBecker: Discoverability, intuition, consistency with other containers.– Dwayne RobinsonNov 21, 2018 at 4:37
1 Answer
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.
-
1Well, you need a function template named
get
in scope forget<T>(v)
to be parsed correctly. Still, better than having to writetemplate
at every turn.– T.C.Feb 6, 2017 at 10:17 -
@T.C.: good point - with the template parameter it isn't directly found via ADL. That may argue for an uncallable function template being declared at global scope (e.g.,
template <typename T> typename T::uncallable get();
; the number of arguments don't really matter...). Feb 6, 2017 at 10:46 -
1Why is
emplace()
a member then? That doesn't seem to need thetemplate
keyword: en.cppreference.com/w/cpp/utility/variant/emplace– ShdNxOct 21, 2019 at 21:40 -
2@ShdNx: the problem is with parsing member function templates with explicitly specified template arguments: while
get<T>(v)
inherently requires thatT
gets specified,v.emplace(a...)
desuces all its template parameters. Hence, the problem doesn’t exist over there. Oct 22, 2019 at 12:56 -
2@DietmarKühl: actually, you need to explicitly specify
T
foremplace
, otherwise it doesn't know what to try to construct from the arguments given. See my earlier link to cppreference.com for examples.– ShdNxOct 22, 2019 at 17:42