【问题标题】:Non-deduced context like 'boost::mpl::identity<T>::type' in standard library?标准库中的非推断上下文,如'boost::mpl::identity<T>::type'?
【发布时间】:2018-09-08 23:56:59
【问题描述】:

想想下面我挖掘的例子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;
  } 

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

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

【问题讨论】:

  • 如果标准中没有任何内容,那么自己实现它并不难:synopsis here 几乎就是它的全部内容
  • @kmdreko 完全正确。我只是想知道它在图书馆里,因为它让我觉得拥有它是一件好事。

标签: c++ c++17 c++-standard-library type-deduction


【解决方案1】:

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;

【讨论】:

    【解决方案2】:

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

    可以如下实现:

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

    【讨论】:

      【解决方案3】:

      std::common_type_t&lt;T&gt; 有效。 From cppreference:

      如果sizeof...(T) 为一(即T...只包含一个类型T0),则成员类型命名为与std::common_type&lt;T0, T0&gt;::type 相同的类型(如果存在);否则没有成员类型。

      因此,std::common_type_t 将为此工作

      【讨论】:

      • 我不一定会推荐它。这样做并不明显
      猜你喜欢
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多