C ++何时需要模板参数? [英] When are template arguments required in C++?
问题描述
我很好奇C ++中何时需要模板参数.
I am curious as to when template arguments are required in C++.
例如,让我们将一个类定义为
For example, let's define a class as
template<typename T> class Add {
T value;
public:
Add(T value) : value(value){};
T operator() (T valrhs){
return value + valrhs;
}
};
如果我们想使用double创建类型为Add的对象,则需要按以下方式定义它,以免出现错误,
If we wanted to create an object of type Add using double, we would need to define it as follows to not get errors,
Add<double> add5 = Add<double>(5.0);
现在让我们考虑定义如下的函数
Lets now consider a function defined as follows,
template<typename T, typename Function> T doOperation (T data, Function f){
return f(data);
}
在代码中,如果要调用doOperation,则不需要模板参数.例如
In code, if one was to make a call to doOperation, no template arguments would be needed. For example,
std::cout << doOperation(5.0, add5);
将输出10.为什么doOperation不需要模板参数,而定义add5则需要模板参数?
would output 10. Why is it that doOperation does not require template arguments but the defining add5 required template arguments?
此外,将有什么方法可以使用函数指针来定义它.我一直试图找出如何使用函数指针作为参数变量而不是第二个模板参数来传递像这样的函子.
Also, would there be any way to define this using function pointers. I have been stuck trying to figure out how to pass a functor like this using a function pointer as a parameter variable rather than a second template argument.
谢谢,我们将为您提供任何帮助.
Thanks, any help is appreciated.
推荐答案
在此代码中
std::cout << doOperation(5.0, add5);
编译器进行函数模板参数推导.
在这一行
Add<double> add5 = Add<double>(5.0);
您需要提供模板参数,因为编译器不会进行类模板参数推导.
you need to provide the template arguments since the compiler won't do class-template argument deduction.
但是,从c ++ 17开始,编译器将执行类模板参数推导,然后编译就可以了
However, from c++17, the compiler will do class-template argument deduction, and then this compiles just fine
Add add5(5.0);
您也可以明确提供扣除指南,因为在某些情况下可能需要
You can provide the deduction guide explicitly as well, since that may be needed in some cases
template<typename T> Add(T) -> Add<T>;
在旁注中,您的类Add
看起来可以用返回lambda的函数模板代替.
On a side-note, your class Add
looks like it could be replaced by a function-template that returns a lambda.
template<typename T>
auto Add (T value) {
return [value] (T valrhs) {
return value + valrhs;
};
}
使用方式如下
auto add5 = Add(5.0);
std::cout << doOperation(5.0, add5);
这篇关于C ++何时需要模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!