我尝试了以下代码:
#include <iostream>
#include <functional>
int anyFunc(int a, int b, int c = 0, int d = 0) {
return a + b + c + d;
}
template <class T, class F>
T callFunc2(const std::function<F> & func, T a, T b) {
return func(a, b);
}
int main() {
std::cout << callFunc2<int, decltype(anyFunc)>(anyFunc, 5, 5) << std::endl;
}
但它会引发错误。海湾合作委员会 9.3.0:
prog.cc: In instantiation of 'T callFunc2(const std::function<_Signature>&, T, T) [with T = int; F = int(int, int, int, int)]':
prog.cc:14:65: required from here
prog.cc:10:16: error: no match for call to '(const std::function<int(int, int, int, int)>) (int&, int&)'
10 | return func(a, b);
| ~~~~^~~~~~
In file included from /opt/wandbox/gcc-9.3.0/include/c++/9.3.0/functional:59,
from prog.cc:2:
/opt/wandbox/gcc-9.3.0/include/c++/9.3.0/bits/std_function.h:683:5: note: candidate: '_Res std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res = int; _ArgTypes = {int, int, int, int}]'
683 | function<_Res(_ArgTypes...)>::
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
/opt/wandbox/gcc-9.3.0/include/c++/9.3.0/bits/std_function.h:683:5: note: candidate expects 4 arguments, 2 provided
也就是说,您需要指定 4 个参数而不是 2 个。但是为什么呢?毕竟,默认情况下有 2 个参数。
编译器如何知道模板中究竟调用了什么?在您看来,它可以是两个或四个参数的函数……默认参数只不过是对特定显式函数调用的提示。
“我想是的”(c)维尼
与往常一样,间接性可以节省:)
此示例显示应避免使用默认参数,而应使用重载函数。
在这种情况下,如有必要,也可以在调用具有默认参数的函数时放置断点。此外,这些参数不会在调用代码中创建(这对于 int 并不重要,但对于较大的对象则非常重要)。