0

Cosider the following example I digged up here on StackOverflow

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

where typename boost::mpl::identity<T>::type prevents the compiler from deducing T based on the type of the second and the third argument. This comes very handy for me, but I cannot use the Boost Library (please do not give me a hard time on that, as it is already a hard time because of that).

The question is now is something equivallent in the standard library directly which I just cannot find?

  • 1
    if there's nothing in the standard, it wouldn't be difficult to implement it yourself: the [synopsis here](https://www.boost.org/doc/libs/1_53_0/libs/mpl/doc/refmanual/identity.html) is pretty much all there is to it – kmdreko Sep 09 '18 at 00:00
  • @kmdreko Totally right. I was just wondering about it being in the library as it struck me to be a nice thing to have. –  Sep 09 '18 at 00:04

3 Answers3

2

C++20 will have std::type_identity. But you don't really have to wait for the standard library to have it. Its entire implementation is:

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

template< class T >
using type_identity_t = typename type_identity<T>::type;
Barry
  • 286,269
  • 29
  • 621
  • 977
1

boost::mpl::identity is a fairly straight-forward template that only provides a type identical to the provided template parameter.

It can be implemented as follows:

template <typename X>
struct identity
{
    typedef X type;
};
kmdreko
  • 42,554
  • 6
  • 57
  • 106
-1

std::common_type_t<T> works. 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.

Thus, std::common_type_t will work for this

Justin
  • 24,288
  • 12
  • 92
  • 142