Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specify default value of std::function

Tags:

c++

lambda

void func(const std::function<void()>& f = empty) {     if(f)         f(); } 

what is the 'empty' should be? I use [](){} . But technically, that is not empty, the f() will execute.

like image 269
jean Avatar asked Nov 20 '15 08:11

jean


People also ask

Does std :: function have a default constructor?

So, why do std::function instances have a default constructor? Without default constructor you wouldn't have to add checks, just like for other, normal arguments of a function. And in those 'rare' cases where you want to pass an 'optional' std::function, you can still pass a pointer to it (or use boost::optional).

Can std :: function be empty?

The stored callable object is called the target of std::function . If a std::function contains no target, it is called empty.

What is default parameter value in c++?

A default argument is a value in the function declaration automatically assigned by the compiler if the calling function does not pass any value to that argument. The values passed in the default arguments are not constant.


2 Answers

void func(const std::function<void()>& f = {}) {     if(f) f(); } 

LIVE DEMO

like image 163
101010 Avatar answered Sep 21 '22 11:09

101010


const std::function<void()>& f = nullptr 

or

const std::function<void()>& f = std::function<void()>() 
like image 42
nh_ Avatar answered Sep 21 '22 11:09

nh_