Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 lambdas as default function arguments

Tags:

c++

c++11

I'm writing a C+11 function that takes a callable as an argument, and I'd like to have that argument default to a no-op function. This is my best attempt so far:

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

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? I'm also wondering if there's a way to avoid explicitly naming the "noop" function. For example:

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

won't compile (in Visual Studio 2012 Update 3), nor will:

void f( int x, int y, std::function<void()> fn= std::function<void()>([](){}) ) { /* ... */ }
like image 798
nonagon Avatar asked Jul 24 '13 19:07

nonagon


1 Answers

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?

No, there are no default noop functions. In this case, you have to create your own (like you did with noop functor object).

like image 57
BЈовић Avatar answered Oct 30 '22 12:10

BЈовић