【问题标题】:Type inference for templatefunctions with templated parameters具有模板化参数的模板函数的类型推断
【发布时间】:2012-04-18 10:16:58
【问题描述】:

编写模板函数的形式是什么(如果有的话),其中参数是模板容器?

例如,我想编写一个通用 sum,它适用于任何可以迭代的容器。鉴于下面的代码,我必须编写例如sum<int>(myInts)。我宁愿只写 sum(myInts) 和从 myInts 包含的类型推断的类型。

/**
 @brief  Summation for iterable containers of numerical type
 @tparam cN                         Numerical type (that can be summed)
 @param[in]  container              container containing the values, e.g. a vector of doubles
 @param[out] total                  The sum (i.e. total)
 */
template<typename N, typename cN>
N sum(cN container) {
    N total;
    for (N& value : container) {
        total += value;
    }
    return total;
}

【问题讨论】:

  • 你知道有std::accumulate 吗?

标签: c++ templates generics types type-inference


【解决方案1】:

我写了这样一个函数

template<typename IT1>
typename std::iterator_traits<IT1>::value_type //or decltype!
function(IT1 first, const IT1 last)
{
    while(first != last)
    {
        //your stuff here auto and decltype is your friend.
        ++first;
    }
    return //whatever
}

这样,它不仅可以与容器一起使用,例如 ostream 迭代器和目录迭代器。

打个电话

function(std::begin(container), std::end(container));

【讨论】:

    【解决方案2】:

    这即使很麻烦,也可以在 C++11 中解决问题:

    template <typename C>
    auto sum( C const & container ) 
         -> std::decay<decltype( *std::begin(container) )>::type
    

    另一种选择只是使用与累积相同的结构:让调用者传递一个带有初始值的额外参数,并使用它来控制表达式的结果:

    template<typename N, typename cN>
    N sum(cN container, N initial_value = N() )
    

    (通过提供默认值,用户可以决定使用值调用它还是提供模板参数——但这需要类型 N 是默认可构造的)

    【讨论】:

    • 这里的箭头是什么?与 lambda 表示法中使用的箭头相同吗?
    • @zenna:它是提供尾随返回类型的语法,是的,它与 lambda 中的用途相同:[](int x) -&gt; double { return 3*x; }
    • 出于某种原因,它 decltype( *std::begin(container) ) 是一个引用(我假设是整数)。
    • @zenna:你是对的,表达式产生一个 lvalue-reference,它可以通过多种方式之一转换为确切的类型,在长路径上,删除引用,然后是 const-volatile 限定条件,或者使用 decay 可以同时完成这两项操作。
    猜你喜欢
    • 2023-03-31
    • 2019-09-12
    • 2018-07-07
    • 2016-07-16
    • 2011-07-26
    • 1970-01-01
    • 2015-02-06
    • 2018-10-23
    • 1970-01-01
    相关资源
    最近更新 更多