c++ - 默认 lambda 作为函数的模板化参数

标签 c++ templates lambda c++17 default-parameters

考虑以下代码

template<bool b, typename T> void foo(const T& t = []() {}) {
  // implementation here
}

void bar() {
  foo<true>([&](){ /* implementation here */ }); // this compiles
  foo<true>(); // this doesn't compile
}

在无法编译的情况下,我会收到以下错误:

error C2672: 'foo': no matching overloaded function found
error C2783: 'void foo(const T&)': could not deduce template argument for 'T'

我认为我想要实现的目标很明确:让 foo 在有和没有客户端提供的 lambda 的情况下被调用。编译器为MSVC++2017版本15.4.4工具集v141。

最佳答案

默认函数参数不是模板参数推导过程的一部分。引用[temp.deduct.partial]/3 :

The types used to determine the ordering depend on the context in which the partial ordering is done:

  • In the context of a function call, the types used are those function parameter types for which the function call has arguments. 141

141) Default arguments are not considered to be arguments in this context; they only become arguments after a function has been selected.

该项目符号和注释表明,由于您没有在对 foo 的调用中为 t 提供参数,因此类型 T 不能被推导。只有在选择调用函数时才会考虑默认的 lambda 参数,而不是之前。

正如所有其他人所指出的那样,解决方案是提供一个不带参数的重载,它将使用您想到的默认 lambda 调用模板化的重载。

关于c++ - 默认 lambda 作为函数的模板化参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47495384/

相关文章:

c++ - 在模板类内 : Use a class method as a template argument for another class method

c++函数代码泛化使用模板

c++ - 如何返回使用 lambda 模板化的对象?

excel - 是否可以使用 Lambda 函数逐步遍历一行数据并对每个第 n 个单元格求和?

c# - 在 C# 中将 Func<T1,bool> 转换为 Func<T2,bool>

c++ - 如果异常被抛出 "through"c 代码会发生什么?

c++ - 如何使用新运算符 C++ 为 void 指针分配内存?

vb.net - 这个带有 Join 的 Linq 查询如何编写为 Lambda?

c++ - 如何将具有 `next()` 方法的类迭代器转换为常规 `begin`/`end` 迭代器对?

c++ - 传递 "No/Null/0"作为引用?