Dave
Dave

Reputation: 299

how do I passing template parameter correctly?

The following code doesn't compile because T is now deduced to be a reference, (either l-value or r-value, but this is not relevant here). So std::vector can't take T as an argument anymore. Does anyone know some way to fix this? Thanks!

template<typename T>
void func( T&& t )
{
    std::vector<T> v;
}

Answer: use std::decay as commented.

Upvotes: 1

Views: 84

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

How arguments with deduced types are declared depends on how you plan to use the argument. In the shown declaration you declared the argument as a forwarding reference which deduces the template argument depending on how the function is called:

  • if the function is called with an lvalue of type X the argument T will be X&
  • if the function is called with an rvalue of type X the argument T will be X

The resulting argument is intended to be forwarded somewhere and is most likely used using

std::forward<T>(t)

If you rather consume your argument (i.e., the argument is pit somewhere) you are probably beat off to take it by value (i.e., you'd use f(T t))and std::move(t) the value into its final destination. You may want to read the argument but not consume it in which case you should probably pass it as T const&.

Assuming the use of a forwarding reference is intentional, you should declare you std::vector with a corresponding type obtained from the deduced type, e.g.

std::vector<std::decay_t<T>> v;

Upvotes: 1

Related Questions