Don*_*uck 18 c++ lambda function c++11
我想使用lambda作为C++函数的参数,但我不知道在函数声明中指定哪种类型.我想做的是:
void myFunction(WhatToPutHere lambda){
//some things
}
Run Code Online (Sandbox Code Playgroud)
我曾尝试void myFunction(auto lambda)和void myFunction(void lambda),但没有这些代码的编译.如果重要,lambda不返回任何东西.
如何在lambin C++函数中使用lambda作为参数?
Jar*_*d42 20
你有两种方法:制作你的功能模板:
template <typename F>
void myFunction(F&& lambda){
//some things
}
Run Code Online (Sandbox Code Playgroud)
或擦除类型 std::function
void myFunction(const std::function<void()/* type of your lamdba::operator()*/>& f){
//some things
}
Run Code Online (Sandbox Code Playgroud)
krz*_*zaq 14
基本上你有两个选择.
使它成为一个模板:
template<typename T>
void myFunction(T&& lambda){
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想(或不能)这样做,您可以使用类型擦除std::function:
void myFunction(std::function<void()> const& lambda){
}
Run Code Online (Sandbox Code Playgroud)
相反,auto根据目前在gcc中实现的TS概念,你的尝试是正确的,它是一个缩写模板.
// hypothetical C++2x code
void myFunction(auto&& lambda){
}
Run Code Online (Sandbox Code Playgroud)
或者有一个概念:
// hypothetical C++2x code
void myFunction(Callable&& lambda){
}
Run Code Online (Sandbox Code Playgroud)
小智 5
像传递一个简单函数一样传递它。只需给它一个名字auto
#include <iostream>
int SimpleFunc(int x) { return x + 100; }
int UsingFunc(int x, int(*ptr)(int)) { return ptr(x); }
auto lambda = [](int jo) { return jo + 10; };
int main() {
std::cout << "Simple function passed by a pointer: " << UsingFunc(5, SimpleFunc) << std::endl;
std::cout << "Lambda function passed by a pointer: " << UsingFunc(5, lambda) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
由指针传递的简单函数:105
由指针传递的 Lambda 函数:15
| 归档时间: |
|
| 查看次数: |
15318 次 |
| 最近记录: |