将 lambda 作为参数传递时重载函数
Overloading function when passing lambda as parameter
我正在尝试在 return 参数为 void 或 T 时实现模板函数。我使用 sfinae 尝试了上述代码的不同变体,但仍然不确定在 lamdba 的情况下这通常是否可行函数参数。
以下代码无法编译:
#include <functional>
template <typename T>
T Apply(const std::function<T()>& func)
{
return func();
}
template <>
void Apply(const std::function<void()>& func)
{
func();
}
int main(int argc, char *argv[])
{
int i1 = Apply([]() { return 10; });
bool b1 = Apply([]() { return true; });
Apply([]() { return; });
return 0;
}
错误:
error C2672: 'Apply': no matching overloaded function found
error C2784: 'T Apply(const std::function<T(void)> &)': could not deduce template argument for 'const std::function<T(void)> &' from 'main::<lambda_536cc9cae26ef6d0d1fbeb7b66a2e26b>'
这是因为 template deduction 需要每个函数参数的完美匹配才能成功推导模板参数。
您需要模板化函数对象本身:
#include <type_traits>
template <class Function, class Return = std::result_of_t<Function()>>
Return Apply(Function func)
{
return func();
}
用法:
#include <iostream>
int main()
{
std::cout << Apply([]() { return 42; }) << "\n";
}
不幸的是,您不能这样做,因为 template argument deduction 中没有考虑隐式转换(从 lambda 闭包类型到 std::function
);代码失败,因为无法推导出 T
。
可以直接使用lambda闭包类型作为参数类型,声明return类型为auto
自动推导。例如
template <typename T>
auto Apply(T func)
{
return func();
}
我正在尝试在 return 参数为 void 或 T 时实现模板函数。我使用 sfinae 尝试了上述代码的不同变体,但仍然不确定在 lamdba 的情况下这通常是否可行函数参数。 以下代码无法编译:
#include <functional>
template <typename T>
T Apply(const std::function<T()>& func)
{
return func();
}
template <>
void Apply(const std::function<void()>& func)
{
func();
}
int main(int argc, char *argv[])
{
int i1 = Apply([]() { return 10; });
bool b1 = Apply([]() { return true; });
Apply([]() { return; });
return 0;
}
错误:
error C2672: 'Apply': no matching overloaded function found
error C2784: 'T Apply(const std::function<T(void)> &)': could not deduce template argument for 'const std::function<T(void)> &' from 'main::<lambda_536cc9cae26ef6d0d1fbeb7b66a2e26b>'
这是因为 template deduction 需要每个函数参数的完美匹配才能成功推导模板参数。
您需要模板化函数对象本身:
#include <type_traits>
template <class Function, class Return = std::result_of_t<Function()>>
Return Apply(Function func)
{
return func();
}
用法:
#include <iostream>
int main()
{
std::cout << Apply([]() { return 42; }) << "\n";
}
不幸的是,您不能这样做,因为 template argument deduction 中没有考虑隐式转换(从 lambda 闭包类型到 std::function
);代码失败,因为无法推导出 T
。
可以直接使用lambda闭包类型作为参数类型,声明return类型为auto
自动推导。例如
template <typename T>
auto Apply(T func)
{
return func();
}