BЈовић
BЈовић

Reputation: 64283

How to decay all variadic template parameters?

Is there a way to decay all types in variable template argument pack into their value types?

For example:

template < typename... T >
void foo( T... ts )    // I do not want to have references here
{
}
template < typename... T >
void bar( T&&... ts )
{
    foo( ts );
}

So, what I would like to do is something like std::decay, but on whole variadic template pack. How to do that?

If I call those functions like this:

struct A{
};
A a;
bar( 3, a, 5.5f );

then I want all to be copied and passed by value to the function foo.

PS: My compiler is gcc 6.2.0 and supports up to c++17

Upvotes: 0

Views: 1784

Answers (1)

T.C.
T.C.

Reputation: 137395

Template argument deduction for template < typename... T > void foo( T... ts ); will always deduce a "decayed" type. (Indeed, the original goal of decay is to perform the type transformations you get when passing something by value.)

Of course, the user can still explicitly write foo<int&>(...). If you care about such things (Murphy/Machiavelli/etc.), a static_assert should suffice:

static_assert((std::is_same_v<T, std::decay_t<T>> && ...), "Hello, Machiavelli!");

Upvotes: 2

Related Questions