“boost::mpl::identity<T>::type"有什么意义?这里? [英] What's the point of "boost::mpl::identity<T>::type" here?

查看:43
本文介绍了“boost::mpl::identity<T>::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&lt;T&gt;::type"有什么意义?这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆