fei*_*tao 3 c++ templates default-arguments
以下 C++ 代码无法编译:
template <typename T>
void f(int, bool = true);
void g()
{
auto h = f<int>;
h(1); // error: too few arguments to function
}
Run Code Online (Sandbox Code Playgroud)
相反,我必须h使用第二个参数调用:
h(1, true);
Run Code Online (Sandbox Code Playgroud)
为什么不起作用h(1)?
有没有一种简单的方法来给模板函数添加别名来绑定模板参数,同时保留默认的函数参数?
h被声明为函数指针,不幸的是它不能指定默认参数。
默认参数只允许出现在函数声明的参数列表中,
and lambda-expressions, (since C++11)不允许出现在函数指针声明、函数引用或 typedef 声明中。
您可以改用 lambda 包装f。例如
auto h = [](int i) { f<int>(i); };
h(1); // -> f<int>(1, true), using f's default argument
Run Code Online (Sandbox Code Playgroud)
或者也在 lambda 上指定默认参数。
auto h = [](int i, bool b = true) { f<int>(i, b); };
h(1); // -> f<int>(1, true), using h, i.e. lambda's default argument
h(1, true); // -> f<int>(1, true), not using default argument
h(1, false); // -> f<int>(1, false), not using default argument
Run Code Online (Sandbox Code Playgroud)