0

I can understand the template parameter restricion. (Or maybe I should call this template specification?) For example:

template<typename T>
void func(vector<T> vec) { /*...*/ }

This means that function func is only available when passed a vector.

However, what I can't understand is the template parameter modification. For example, one possible simplified implemention of std::forward:

template <typename T>
T&& forward(typename std::remove_reference<T>::type& t) noexcept {
    return static_cast<T&&>(t);
}

Here, the type of t has been modified to remove its reference.

It makes little sense to me. In my opinion, if T has been already deducted from the argument of std::forward, then it can be modified by std::remove_reference. But T it self is just one part of the type of parameter t.

Additionally, the form of type restriction and modification looks almost the same. I can't help myself to thinking that T is actually some kind of restriction of the type of t in the example above.

Can somebody figure out what's happening when modifing a template parameter type?

Gorun
  • 134
  • 6
  • 1
    *if `T` has been already deducted from the argument of `std::forward`* - `T` can't be deduced from `t`, you should specify the template parameter `T` like `std::forward(t)`, then the type of `t` is a reference to `std::remove_reference::type`. – 273K May 10 '23 at 15:12
  • 1
    Read about [non-deduced context](https://stackoverflow.com/a/25245676/12002570). It has almost the same example as in your question. – Jason May 10 '23 at 15:14
  • @273K Wow, thanks. I suddenly understand why ```std::forward``` must be used with ```T``` specified. This example is not ok here. – Gorun May 10 '23 at 15:18
  • @Jason My problem is resolved. Thanks. – Gorun May 10 '23 at 15:30

0 Answers0