使用lambda进行模板类型推导
Template Type Deduction with Lambdas
我面临的问题很简单。给定以下代码:
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;
}
生活例子
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 在 lambda 捕获中声明的变量的类型推导
- C++ 模板类型的静态 lambda 成员的构造
- Clang 工具,用于提取给定 lambda 类型的 lambda 主体
- 如果 lambda 没有指定的类型,std::function 如何接受 lambda?
- Lambda可以用作非类型模板参数吗
- 如何确定捕获不可复制参数的 lambda 的类型?
- 如何制作可以接受任何类型的参数的 std::函数和 lambda
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 运算符中的不同类型? 具有无捕获,相同的签名,lambda
- 通过参数传递 lambda(无函数类型模板)
- 有没有办法根据 lambda 参数返回类型部分专用化我的模板化函数?
- 如何推导lambda的返回类型
- 尽管显式声明了返回类型,但对lambda的调用是不明确的
- 是否创建具有不同返回类型的lambda
- 防止 lambda 的返回类型扣除
- 在 lambda 函数 g++-4.8 中调用继承的受保护子类型
- 在 lambda 中从引用类型捕获的值的类型,不使用通用捕获
- 我可以让返回类型自动处理具有相同签名但捕获不同内容的 lambda 吗?
- 复制分配C++相同类型的 lambda