Reputation: 355
What is the difference between using "typename
" before the return type of a function and without using it at the declaration of a function like the following below?
And what is different if we don't use it at all?
template< class T > typename std::remove_reference<T>::type&& move( T&& t );
template< class T > std::remove_reference_t<T>&& move( T&& t ) ;
Upvotes: 2
Views: 129
Reputation: 32952
What is the purpose of using '
typename
' keyword right before the return type of a function?
In std::remove_reference<T>::type
, the ::type
is dependent on the template type T
. The compiler (until C++20), doesn't know this, and one needs to tell that, so that compiler understands it is a type. That is the reason why typename
keyword is.
Read more: When is the "typename" keyword necessary?
The second std::remove_reference_t<T>
, is a template type alias, which looks like:
template< class T >
using remove_reference_t = typename remove_reference<T>::type; (since C++14)
And allows you to save some typing (aka. for convenience).
What is different if we don't use it at all?
Since C++20, you can simply write with or without typename
keyword, prior to that compiler may not interpret it as a type.
Read more: Why don't I need to specify "typename" before a dependent type in C++20?
Upvotes: 5
Reputation: 46
https://en.cppreference.com/w/cpp/keyword/typename
(2nd point in the link)
- Inside a declaration or a definition of a template, typename can be used to declare that a dependent qualified name is a type.
When you are using foo_type::bar
, the compiler can't ensure what bar
is, maybe a member variable or a type or anything else. Hence you have to at a precede typename
to hint to the compiler that it is a typename.
Upvotes: 2