C++11 lambda 作为默认函数参数

标签 c++ c++11

我正在编写一个 C+11 函数,它接受一个可调用对象作为参数,并且我希望该参数默认为无操作函数。这是我迄今为止最好的尝试:

const std::function<void()> noop= [](){};
void f( int x, int y, std::function<void()> fn= noop ) { /* ... */ }

我想知道标准库是否为我提供了一个“noop”std 函数,或者我是否需要像上面那样编写自己的函数?我还想知道是否有办法避免显式命名“noop”函数。例如:

void f( int x, int y, std::function<void()> fn= [](){} ) { /* ... */ }

不会编译(在 Visual Studio 2012 Update 3 中),也不会:

void f( int x, int y, std::function<void()> fn= std::function<void()>([](){}) ) { /* ... */ }

最佳答案

I'm wondering whether the standard libraries provide a "noop" std function for me, or do I need to write my own as I have above?

不,没有默认的 noop 函数。在这种情况下,您必须创建自己的(就像您对 noop 仿函数对象所做的那样)。

关于C++11 lambda 作为默认函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17843003/

相关文章:

c++ - 使用 memcpy 时出现内存错误?

c++ - 为什么结构化绑定(bind)禁用 RVO 并继续返回语句?

C++/OpenGL : How does Tesselation work?

c++ - 相机的旋转方向在一段时间后自行反转

python - Pybind - 使用指向派生类的共享指针调用函数

c++ - 将字符串文件路径转换为唯一标识符

c++ - 为什么wxWidgets在调用new之后从不调用delete?

c++ - 如何从 decltype 引用中获取值类型?

c++ - 二叉搜索树帮助插入功能

c++ - C 中的信赖域反射算法库