What#39;s the point of quot;boost::mpl::identitylt;Tgt;::typequot; here?(“boost::mpl::identitylt;Tgt;::type有什么意义?这里?)
问题描述
我正在检查 clamp代码>在boost中:
I was checking the implementation of clamp in boost:
template<typename T, typename Pred>
T const & clamp ( T const& val,
typename boost::mpl::identity<T>::type const & lo,
typename boost::mpl::identity<T>::type const & hi, Pred p )
{
// assert ( !p ( hi, lo )); // Can't assert p ( lo, hi ) b/c they might be equal
return p ( val, lo ) ? lo : p ( hi, val ) ? hi : val;
}
如果我查看文档,identity 返回模板参数不变.
If I look up the documentation, identity returns the template argument unchanged.
身份元功能.返回 X 不变.
The identity metafunction. Returns X unchanged.
那么在这里使用它有什么意义?
So what's the point of using it here?
typename boost::mpl::identity<T>::type 不是等价于 T 吗?
推荐答案
nested-name-specifier 创建一个非推导的上下文.因此,编译器不会尝试根据声明为的第二个和第三个参数来推断类型 T:
A nested-name-specifier creates a non-deduced context. Therefore, a compiler will not attempt to deduce type T based on the second and third parameters declared as:
typename boost::mpl::identity<T>::type const &
Type T 只会根据第一个参数的类型推导,然后用于实例化其余参数的类型.使用 identity 类型是防止对某些参数进行模板参数类型推导的常见技巧,否则会在参数类型不同但使用相同类型的模板参数的情况下导致模棱两可的调用错误.有时也可能希望不让编译器自动推断类型,而是强制调用者自己做.
Type T will be deduced only based on the type of the first argument, and then used to instantiate the types of the rest parameters. Using the identity type is a common trick to prevent template argument type deduction on certain parameters, that otherwise would result in an ambiguous call error in case the types of arguments differ, but utilize the same type template parameter. It can be also sometimes desired not to let a compiler automatically infer the type, and force a caller do it on his/her own.
这篇关于“boost::mpl::identity<T>::type"有什么意义?这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“boost::mpl::identity<T>::type"有什么意义?这里?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
