1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
struct data
{
inline double someExampleCost( unsigned int, double ) const { return 0 ; }
};
//using cost_fn_type = std::function< double( unsigned int, double ) > ;
typedef std::function< double( unsigned int, double ) > cost_fn_type ;
void foo( double w, std::vector< unsigned int >& seq, const cost_fn_type& cost_fn )
{
std::sort( std::begin(seq), std::end(seq),
[&cost_fn,w]( unsigned int a, unsigned int b ) { return cost_fn( a, w ) < cost_fn( b, w ) ; } ) ;
}
template < typename FN > void bar( double w, std::vector< unsigned int >& seq, FN&& fn )
{
const auto cost_fn = std::forward<FN>(fn) ; // perfect forwarding, required only if fn is not passed by value
std::sort( std::begin(seq), std::end(seq),
[&cost_fn,w]( unsigned int a, unsigned int b ) { return cost_fn( a, w ) < cost_fn( b, w ) ; } ) ;
}
int main()
{
std::vector< unsigned int > seq { 0, 1, 2, 3 } ;
data object ;
// using namespace std::placeholders ;
// foo( 100, seq, std::bind( &data::someExampleCost, &object, _1, _2 ) ) ;
foo( 100, seq, [&object]( unsigned int a, double b){ return object.someExampleCost(a,b) ; } ) ;
bar( 100, seq, [&object]( unsigned int a, double b){ return object.someExampleCost(a,b) ; } ) ;
}
|