In some cases std::function
can replace inheritance. The following two code snippets are very similar (about the same costs when calling the function, almost the same usage in signatures and in most cases std::function does not require us to make an extra copy of A
as well):
struct Function
{
virtual int operator()( int ) const =0;
};
struct A
: public Function
{
int operator()( int x ) const override { return x; }
};
Using std::function
, we can rewrite this as
using Function = std::function<int (int)>;
struct A
{
int operator()( int x ) const { return x; }
};
In order to make more clear, how the two snippets are related: both of them can be used in the following way:
int anotherFunction( Function const& f, int x ) { return f( x ) + f( x ); }
int main( int argc, char **argv )
{
A f;
anotherFunction( f, 5 );
return 0;
}
The latter approach is more flexible, because we do not have to derive our classes from some common base class. The only relationship between Function
-like objects is based on their capabilities. In terms of object-orientated programming it might be considered less clean (but not in terms of functional programming, of course).
Apart from that, are there any other differences between the two solutions? Are there any general guidelines when to use which of the solutions or is it only a matter of personal preference? Are there any cases where one solution out-performs the other?