Pav*_*aka 4 c++ default-arguments
这是使用的简单示例std::function
#include <iostream>
#include <functional>
//A function that sums two numbers.
//Arguments having default values.
void SumOfTwoNumbers(int a = 42, int b = 42)
{
std::cout << "Sum of two numbers :: " << a + b << std::endl;
}
int main()
{
std::function<void(int, int)> testFunc = SumOfTwoNumbers;
SumOfTwoNumbers(); //Works
testFunc(); //Compile time error
testFunc(40, 40); //Works
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在main函数中,共有三个函数调用。第一个和最后一个有效。而没有任何参数的第二次调用testFunc()会给出编译时错误。
它不应该考虑默认参数并成功执行吗?
不,函数参数的默认值不是函数签名的一部分。它们仅在调用站点进行评估。
您可以使用 lambda,但随后您需要重新定义默认值:
auto testFunc = [](int a = 42, int b = 42) { SumOfTwoNumbers(a, b); };
Run Code Online (Sandbox Code Playgroud)
...并且将这样的 lambda 存储在 a 中将std::function再次导致相同的问题,因为 lambda 的签名也是void(int, int).
但是,您可以定义自己的std::function具有多个 operator()重载的包装函子(而不是使用 ):
struct {
void operator()() { SumOfTwoNumbers(42, 42); }
void operator()(int a) { SumOfTwoNumbers(a, 42); }
void operator()(int a, int b) { SumOfTwoNumbers(a, b); }
} testFunc;
Run Code Online (Sandbox Code Playgroud)