标准库中的 'boost::mpl::identity<T>::type' 之类的非推导上下文?

Non-deduced context like 'boost::mpl::identity<T>::type' in standard library?

考虑下面这个我挖出来的例子here on Whosebug

  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;
  } 

其中 typename boost::mpl::identity<T>::type 阻止编译器根据第二个和第三个参数的类型推导 T。这对我来说非常方便,但我不能使用 Boost Library(请不要为此难过我,因为这已经很困难了)。

现在的问题是标准库中直接存在我找不到的等价物?

std::common_type_t<T> 有效。 From cppreference:

If sizeof...(T) is one (i.e., T... contains only one type T0), the member type names the same type as std::common_type<T0, T0>::type if it exists; otherwise there is no member type.

因此,std::common_type_t 将适用于此

boost::mpl::identity 是一个相当简单的模板,它只提供与提供的模板参数相同的 type

可以这样实现:

template <typename X>
struct identity
{
    typedef X type;
};

C++20 将有 std::type_identity。但是您实际上不必等待标准库拥有它。它的整个实现是:

template< class T >
struct type_identity {
    using type = T;
};

template< class T >
using type_identity_t = typename type_identity<T>::type;