c++ - 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++ 标准,为什么?
解决方案
从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);
推荐阅读
- react-native - Admob 广告未显示在 React Native Signed Apk 中
- c# - 检查 ASP.NET Core 中是否允许匿名
- python - 将包含熊猫系列的列转换为特征
- php - Codeigniter:更新到 CI4 后,Loader 类出错
- postgresql - 为数据库中所有还没有主键的表添加主键
- python - __index__ 返回非int(类型NoneType):使用张量动态形状创建自定义层
- c# - 无法使用来自 UWP-App 的受信任连接连接到 SQL Server
- arrays - 如何在角度分量中显示多个对象的数据或如何将它们添加到一个数组中
- c++ - 自定义类函数导致的内存错误
- ios - 如何根据里面的内容调整表格视图单元格的大小?