【问题标题】:Alias a template function with default parameters为具有默认参数的模板函数起别名
【发布时间】:2021-06-17 00:49:37
【问题描述】:

以下 C++ 代码无法编译:

template <typename T>
void f(int, bool = true);

void g()
{
    auto h = f<int>;
    h(1); // error: too few arguments to function
}

相反,我必须使用第二个参数调用h

h(1, true);

为什么h(1) 不起作用?

有没有一种简单的方法可以给模板函数取别名以绑定模板参数,同时保留默认函数参数?

【问题讨论】:

  • 别名仅适用于类型。默认参数值不是函数签名的一部分,因此它们不能通过类型别名保留。

标签: c++ templates default-arguments


【解决方案1】:

h被声明为函数指针,不幸的是它不能指定default arguments

默认参数只允许在函数声明 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

或者在 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

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多