从 lambda 中推导模板参数

Template argument deduction from lambda

本文关键字:参数 lambda      更新时间:2023-10-16

我正在尝试编写一个函数,该函数基本上将一种类型模板化的类的实例转换为另一种类型上模板化的同一类的实例。我想避免在调用函数时显式声明模板类型。

这是我正在尝试执行的操作的最小可编译示例:

template<class T> class container {};
template <class A, class B, template <class C> class Container>
Container<B> transform(Container<A> c, B(func)(A))
{
return Container<B>{};
}
int do_something(int in)
{
return in + 1;
}
int main()
{
container<int> c{};
//this one doesn't work:
//transform(c, [](int in) -> int { return in + 1; });
//these are fine:
transform<int, int>(c, [](int in) -> int { return in + 1; });
transform(c, do_something);
return 0;
}

取消注释掉第一个transform调用会导致编译错误:

Visual Studio 2017:

error C2784: 'Container<B> transform(Container<A>,B (__cdecl *)(A))': could not deduce template argument for 'B (__cdecl *)(A)' from 'test::<lambda_afc081691b59f849887abca17e74b763>'

无论 coliru.stacked-crooked.com 默认使用哪个版本的 g++:

main.cpp:4:14: note:   template argument deduction/substitution failed:
main.cpp:18:52: note:   mismatched types 'B (*)(A)' and 'main()::<lambda(int)>'
transform(c, [](int in) -> int { return in + 1; });
^

这是否意味着编译器不可能推断出lambda的签名,即使它已经像这样明确定义?

我知道我可以像这样重写我的转换函数:

template <class A, template <class C> class Container, class F>
auto transform(Container<A> c, F func)->Container<decltype(func(A{}))>
{
return Container<decltype(func(A{}))>{};
}

但是现在函数签名的可读性有点差,如果我提供不合适的函数,我收到的错误消息非常不友好。使用std::function<B(A)>也无济于事。

有没有办法将更严格指定的函数参数与 lambda 一起使用,而无需显式添加模板类型?

您需要将无捕获的 lambda 转换为执行操作的静态函数。实际上,通过应用一元+运算符可以相当容易地调用该转换。

transform(c, +[](int in) -> int { return in + 1; });

由于无捕获lambda的闭包类型有一个转换运算符要ret(*)(params),编译器在遇到+时会调用它。这是因为您实际上可以将+应用于指针类型。

[expr.unary.op/7]

一元 + 运算符的操作数应具有算术、无作用域枚举或指针类型,结果是参数的值。整型提升对整型或枚举操作数执行。结果的类型是升级的操作数的类型。

BA不能从lambda中B(func)(A)推断出来。

您可以将模板更改为更通用,例如:

template <template <typename...> class Container, typename Ts...>
auto transform(const Container<Ts...>& c, F f)
-> Container<std::decay_t<decltype(f(*c.begin())>>
{
return {};
}