我正在学习一些基本的 cpp,我发现我们可以将 lambda 函数传递给接受 std::function 的函数,如下所示:
int someFunction(std::function<int(int, int)> sum) {
return sum(1,3);
}
我对 std::function 如何将模板类型作为“int(int, int)”感到困惑,通常我只看到类采用像 someClass
我们如何定义采用“int(int, int)”等模板类型的类?
我试过像这样声明类
template<typename A(typename B)> // --> this just gives an syntax error.
class SomeClass {};
起初,你的例子不应该编译。
int someFunction(std::function<int(int)> sum) {
return sum(1,3);
}
/*
std::function<int(int)>
^ ^
| |
return parameter
type
So, calling sum(1,3) would require function<int(int, int) as you are passing two parameters and returning a value.
*/
更多例子
/*
The structure is "return_type(param1, param2, ..)" for the function and the following
`[]` is used for variable capture (by value [x] or by reference [&x]) that resides out the function.
*/
// takes one param and returns nothing
function<void(int)> print = [](auto i) {
court<<i<<endl;
}
// takes two params and returns the sum
function<int(int, int)> sum = [](auto i, auto j) {
return i + j;
}
// takes one param and returns with added 2
function<int(int)> sum = [](auto i) {
return i + 2;
}
感谢@Raildex 的评论,我正在回答我自己的问题。基本上问题中的类型 int(int, int) 指的是一个函数指针,它接受 2 个整数并返回一个整数。
所以一个示例类可以是:
template<typename T>
class SomeClass {
public:
void someMethod(T sum) {
cout << sum(1, 3) << endl;
}
};
SomeClass someClass;
// the template type is not required here, but has been added just for clarity.
someClass.someMethod<int(int, int)>([](int a, int b){return a + b;});