about std::function

I have this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Foo
{
private:
	std::function<void()> fun;
public:
	void setFun(std::function<void()> _fun)
	{
		fun = _fun;
	}
	void onFun()
	{
		if( ??? ) // check if fun is assigned
			fun();
	}
};


How to check if function is assigned?

Or should i just assign default empty function in constructor?
1
2
3
4
Foo()
{
    setFun( []{} );
}

Last edited on
> Or should i just assign default empty function in constructor?

No. The default constructor of std::function<> intialises the object with a null target.


> How to check if function is assigned?
std::function<> has an implicit conversion to bool - true if there is a valid callable target, false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
include <functional>
#include <iostream>
#include <typeinfo>
#include <cstdlib>

int main()
{
    std::function< void() > f ; // default constructor - no target
    std::cout << ( f ? "has a valid target" : "there is no target" ) << '\n' ;

    f = std::rand ; // target is std::rand
    std::cout << ( f ? "has a valid target" : "there is no target" ) << '\n' ;

    f = []() { std::cout << "closure\n" ; } ; // target is closure
    std::cout << ( f ? "has a valid target" : "there is no target" ) << '\n' ;

    f = nullptr ; // nullptr - no target
    std::cout << ( f ? "has a valid target" : "there is no target" ) << '\n' ;
}
Thanks.
Topic archived. No new replies allowed.