浅墨浓香

想要天亮进城,就得天黑赶路。

导航

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

Posted on 2020-04-16 11:28  浅墨浓香  阅读(256)  评论(0编辑  收藏  举报

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();