使用lambda进行模板类型推导

Template Type Deduction with Lambdas

本文关键字:类型 lambda 使用      更新时间:2023-10-16

我面临的问题很简单。给定以下代码:

template <typename ReturnType, typename... Args>
auto CallIt( ReturnType( *method )( Args... ) )
{
    return method;
}
auto test = CallIt( [] ( int a, int b )
{
    return a > b;
} );

我得到的错误(使用VS13与2013年11月CTP编译器)是:

无法从main::

我明白lambda不是函数指针,但lambda不捕获可以分配给匹配签名的函数指针。如果您显式指定模板参数,则可以这样做。我希望看到一种无需显式指定模板参数就可以工作的方法。提前感谢您的帮助。

正如Marco A.提供的答案的注释中所指出的,可能有一个解决方案,使用lambda类上的一元+操作符,有效地将其转换为函数指针。但是,在请求的IDE/编译器组合中,我收到以下警告转换错误:

从"lambda []bool (int a, int b)->bool"对内置类型应用:

function "lambda []bool (int a, int b)->bool::operator bool (*)(int a, int b)() construct "

function "lambda []bool (int a, int b)->bool::operator bool (*)(int a, int b)() construct "

function "lambda []bool (int a, int b)->bool::operator bool (*)(int a, int b)() construct "

function "lambda []bool (int a, int b)->bool::operator bool (*)(int a, int b)() construct "

这个智能感知错误说明了指定

生成的编译错误

错误C2593: 'operator +'有歧义

1)添加适当的尾随返回类型

2)如果你想传递一个函数指针,让lambda符合

template <typename ReturnType, typename... Args>
auto CallIt( ReturnType( *method )( Args... ) ) -> ReturnType(*)(Args...)
{
    return method;
}
auto test = CallIt( +[] ( int a, int b )
{
    return a > b;
} );
<<p> 生活例子/strong>
编辑:似乎MSVC2013有点问题。作为一种解决方法,您可以尝试以下方法是否暂时有效:
#include <iostream>
#include <functional>
using namespace std;
template <typename ReturnType, typename... Args>
auto CallIt( std::function<ReturnType( Args... )> method ) -> std::function<ReturnType( Args... )>
{
    return method;
}
int main() {
    std::function<bool(int,int)> lambda = [] ( int a, int b ) { return a > b; };
    auto test = CallIt( lambda );
    cout << test(4,1);

    return 0;
}

生活例子