gpt4 book ai didi

c++ - 将 lambda 作为参数传递时重载函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:39 25 4
gpt4 key购买 nike

我正在尝试在返回参数为 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>'

wandbox live

最佳答案

不幸的是,您不能那样做,因为 template argument deduction 中没有考虑隐式转换(从 lambda 闭包类型到 std::function) ;代码失败,因为无法推导出 T

可以直接使用lambda闭包类型作为参数类型,声明返回类型为auto自动推导。例如

template <typename T>
auto Apply(T func)
{
return func();
}

LIVE

关于c++ - 将 lambda 作为参数传递时重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com