第3章 非类型模板参数:3.2 非类型函数模板参数

3.2 Nontype Function Template Parameters

3.2 非类型函数模板参数

You can also define nontype parameters for function templates. For example, the following function template defines a group of functions for which a certain value can be added:

你也可以为函数模板定义非类型参数。例如,下面的函数模板定义了一组可以增加特定值的函数:

template<int Val, typename T>
T addValue (T x)
{
    return x + Val;
}

These kinds of functions can be useful if functions or operations are used as parameters. For example, if you use the C++ standard library you can pass an instantiation of this function template to add a value to each element of a collection:

如果需要把函数或操作当作参数的话,那么这类函数就非常有用。例如,借助于C++标准库,你可以传递这个函数模板给集合中的每一个元素,让他们都增加一个整数值:

std::transform (source.begin(),          //源的开始位置
                       source.end(),     //源的结束位置
                       dest.begin(),     //目标的开始位置
                       addValue<5,int>); //操作

The last argument instantiates the function template addValue<>() to add 5 to a passed int value. The resulting function is called for each element in the source collection source, while it is translated into the destination collection dest.

在上面的调用中,最后一个实参将addValue()函数模板实例化成:让int元素增加5。源集合(source)中的每一个元素都会调用实例化后addValue()函数,并把调用结果放入目标集合(dest)中。

 

Note that you have to specify the argument int for the template parameter T of addValue<>(). Deduction only works for immediate calls and std::transform() need a complete type to deduce the type of its fourth parameter. There is no support to substitute/deduce only some template parameters and the see, what could fit, and deduce the remaining parameters.

注意,必须指定addValue()的模板参数为int类型。推导只适用于立即调用,并且std::transform()需要一个完整的类型才能推导出其第4个参数的类型。不支持先部分替换或推导模板参数的类型,然后再根据具体情况去推导其余的模板参数。

Again, you can also specify that a template parameter is deduced from the previous parameter. For example, to derive the return type from the passed nontype:

同样,你也可以指定一个从上一个参数推导而来的模板参数。例如,要传递从非类型中派生出来的返回类型:

template<auto Val, typename T = decltype(Val)>
T foo();

or to ensure that the passed value has the same type as the passed type:

或者为了确保传递的值与其类型相同:

template<typename T, T Val = T{}>
T bar();

 

原文链接: https://www.cnblogs.com/5iedu/p/12711523.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    第3章 非类型模板参数:3.2 非类型函数模板参数

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/392626

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月3日 下午2:53
下一篇 2023年4月3日 下午2:54

相关推荐