首页 > 解决方案 > c++ 一致性是否使用 decltype 来帮助进行模板推导?

问题描述

鉴于这两个功能:

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++ 标准,为什么?

标签: c++templatestemplate-meta-programmingdecltype

解决方案


template_argument_deduction,在非推导上下文中:

在以下情况下,用于构成 P 的类型、模板和非类型值不参与模板参数推导

[..]

2) 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);

推荐阅读