2

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 ) ;
JeJo
  • 30,635
  • 6
  • 49
  • 88
Crackie
  • 203
  • 6

2 Answers2

5

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?

JeJo
  • 30,635
  • 6
  • 49
  • 88
2

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.

chrysante
  • 2,328
  • 4
  • 24
NoReason
  • 46
  • 4
  • 3
    If `foo_type` is dependent on a template parameter. Also you don't mention what the differences between the two declarations are. – chrysante Aug 03 '23 at 08:28
  • 1
    I wanted to say, without `typename`, the code is uncompilable. But @JeJo mentioned that it's correct only if the standard before c++20, and he provided lots of detail explanation and related articles too. I think this answer is actually too simple. – NoReason Aug 03 '23 at 09:32