Reputation: 161
for example, I can do something like:
void foo(int i)
{
std::cout << "fo is called with: " << i << "\n";
}
int main()
{
std::function<void(int)> fo = std::bind(&foo, std::placeholders::_1);
fo(5);
}
and output
fo is called with: 5
now I'm curious about if I can make a std::function that receive a std::function as argument,so I think of some function like:
void foAndFo(function<void(int)> foo)
{
std::function<void(int)> fo = std::bind(&foo, std::placeholders::_1);
fo(5);
}
but this can even not been compiled.
now I changed to something may call function pointer.
using foType = void(*)(int);
void foAndFo(foType foo)
{
std::function<void(int)> fo = std::bind(&foo, std::placeholders::_1);
fo(5);
}
now it can be compiled.But now I cannot std::bind it like:
int main()
{
std::function<foType> fo2 = std::bind(&foAndFo,std::placeholders::_1); //error
}
is it possible to use std::function as argument of std::function?
Upvotes: 1
Views: 581
Reputation: 11550
This is possible. Just drop the &
before foo
here:
void foAndFo(function<void(int)> fo)
{
std::function<void(int)> fo = std::bind(/*&*/foo, std::placeholders::_1);
fo(5);
}
The difference is that if foo
is a void(int)
, both foo
and &foo
can be inserted where a function is expected. On the other hand, if foo
is a std::function
then the two are quite different: foo
can be passed for a const std::function&
, but &foo
is a std::function*
, a pointer to an object of the type std::function
. The latter is not Callable.
Minimal working example:
#include <iostream>
#include <functional>
void foo(int i)
{
std::cout << "fo is called with: " << i << "\n";
}
int main()
{
std::function<void(int)> fo = std::bind(foo, std::placeholders::_1); // or &foo, both work
std::function<void(int)> fo2 = std::bind(fo, std::placeholders::_1); // Error if &fo is used
fo2(5);
}
Upvotes: 2