[英]Type inference for templatefunctions with templated parameters
What is the form (if there is one) to write template functions, where arguments are templated containers?编写模板函数的形式(如果有的话)是什么形式,其中 arguments 是模板化容器?
For example I want to write a generic sum, which will work on any container which can be iterated over.例如,我想写一个通用的总和,它适用于任何可以迭代的容器。 Given the code below I have to write for example sum<int>(myInts)
.鉴于下面的代码,我必须编写例如sum<int>(myInts)
。 I would prefer to just write sum(myInts)
and the type to be inferred from the type which myInts contains.我宁愿只写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;
}
I write such a function like this我这样写一个function
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
}
This way it will work with more than just containers, for example ostream iterators and directory iterators.这样,它不仅可以与容器一起使用,例如 ostream 迭代器和目录迭代器。
Call like像这样打电话
function(std::begin(container), std::end(container));
This, even if cumbersome, can do the trick in C++11:这个,即使很麻烦,也可以在 C++11 中解决问题:
template <typename C>
auto sum( C const & container )
-> std::decay<decltype( *std::begin(container) )>::type
Another option is just using the same structure that accumulate does: have the caller pass an extra argument with the initial value and use that to control the result of the expression:另一种选择是使用与 accumulate 相同的结构:让调用者传递一个带有初始值的额外参数,并使用它来控制表达式的结果:
template<typename N, typename cN>
N sum(cN container, N initial_value = N() )
(By providing a default value, the user can decide to call it with a value or else provide the template argument --but this requires the type N to be default constructible) (通过提供一个默认值,用户可以决定用一个值调用它,或者提供模板参数——但这需要类型 N 是默认可构造的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.