Reputation: 299
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
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:
X
the argument T
will be X&
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