【发布时间】:2018-01-24 14:33:23
【问题描述】:
我正在尝试在返回参数为 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>'
【问题讨论】:
标签: c++ templates lambda sfinae