c++ 一致性是否使用 decltype 来帮助进行模板推导?
Is c++ conformance use decltype to help on template deduction?
给出这两个函数:
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 );
}
我看到几乎在 gcc 9 中,类型推导总是在 Print2
上起作用,但在 Print1
上不起作用
unsigned int i = 0;
Print1( i, 0 ); // dont work (cant do type deduction)
Print2( i, 0 ); // work
这是 decltype
技术 c++ 一致性吗?为什么?
来自 template_argument_deduction,在非推导上下文中:
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:
所以在
template <typename T> void Print2(const T& aValue, const decltype(aValue)& aDefaultValue)
aDefaultValue
的类型不可推导。
T
仅从 aValue
推导出来。
在 C++20 中,替代方法是使用 std::type_identity
:
template <typename T>
void Print2(const T& aValue, std::type_identity_t<const T&> aDefaultValue);
给出这两个函数:
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 );
}
我看到几乎在 gcc 9 中,类型推导总是在 Print2
上起作用,但在 Print1
unsigned int i = 0;
Print1( i, 0 ); // dont work (cant do type deduction)
Print2( i, 0 ); // work
这是 decltype
技术 c++ 一致性吗?为什么?
来自 template_argument_deduction,在非推导上下文中:
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:
所以在
template <typename T> void Print2(const T& aValue, const decltype(aValue)& aDefaultValue)
aDefaultValue
的类型不可推导。
T
仅从 aValue
推导出来。
在 C++20 中,替代方法是使用 std::type_identity
:
template <typename T>
void Print2(const T& aValue, std::type_identity_t<const T&> aDefaultValue);