Isaac Pascual
Isaac Pascual

Reputation: 492

Is c++ conformance use decltype to help on template deduction?

Given this two function:

template <typename T> void Print1( const T& aValue, const T& aDefaultValue )
{
    if( aValue != aDefaultValue ) std::cout << aValue << std::endl;
}

template <typename T> void Print2( const T& aValue, const decltype(aValue)& aDefaultValue )
{
    Print1<T>( aValue, aDefaultValue );
}

I see that almost in gcc 9 type deduction works always on Print2 but not on Print1

unsigned int i = 0;
Print1( i, 0 ); // dont work (cant do type deduction)
Print2( i, 0 ); // work

Is this decltype technique c++ conformance and why?

Upvotes: 1

Views: 45

Answers (1)

Jarod42
Jarod42

Reputation: 217593

From template_argument_deduction, in non-deduced contexts:

In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction

[..]

2) The expression of a decltype-specifier:

So in

template <typename T> void Print2(const T& aValue, const decltype(aValue)& aDefaultValue)

type of aDefaultValue is non deducible. T is only deduced from aValue.

In C++20, alternative is to use std::type_identity:

template <typename T>
void Print2(const T& aValue, std::type_identity_t<const T&> aDefaultValue);

Upvotes: 4

Related Questions