As per the documentation(http://www.cplusplus.com/reference/functional/function/), which says that:
Class that can wrap any kind of callable element (such as functions and function objects) into a copyable object, and whose type depends solely on its call signature (and not on the callable element type itself).
How to comprehend that the type of std::function
depends solely on its call signature(and not on the callable element type itself)? Could somebody make it clear by giving some simple examples?I would be greatful to have some help with this question.
The template type effectively denotes a function signature (excluding name of course).
std::function<bool(Bar const&, Foo const&)>
Can hold a functor, member function pointer, function pointer or lambda. But the callable must have the bool (Bar const&, Foo const&)
signature.
class Foo {};
class Bar {};
class FunctorEx
{
public:
bool operator()(Bar const&, Foo const&)
{
return true;
}
} FunctorExInst;
class MemFunction
{
public:
bool MemFunctionEx(Bar const&, Foo const&)
{
return true;
}
} MemFunctionInst;
bool FunctionEx(Bar const&, Foo const&)
{
return true;
}
int main()
{
auto LambdaEx = [] (Bar const&, Foo const&) -> bool
{
return true;
};
std::function<bool(Bar const&, Foo const&)> exFunctionVar;
exFunctionVar = std::bind(&MemFunction::MemFunctionEx, &MemFunctionInst, std::placeholders::_1, std::placeholders::_2);
exFunctionVar = FunctorExInst;
exFunctionVar = FunctionEx;
exFunctionVar = LambdaEx;
}
Despite MemFunctionInst
, FunctorExInst
, FunctionEx
, LambdaEx
all being of different types, they can all be assigned to the same std::function
variable due to a technique called type erasure.