Could boost::function accept arbitrary arguments?

1
2
3
//B is an arbitrary argument
//N is the size of f
boost::function<int(int, B)> f[N] = {boost::bind(....), .....};


B maybe type point, type myRBTree and so on

Thanks a lot

Last edited on
Not directly like that because the callpoint of the function must have at least two parameters on it -- one being an int and the other a B. B has to be known at the callpoint, unless B is polymorphic (in which case you'll need to take a B by reference or pointer).

Alternatives are to make B a boost::variant<> type if you know the set of possible types at compile time and the set is relatively small, or a boost::any otherwise. Though boost::any is icky.
Thanks a lot, I would try to find out what is boost::variant and boost::any
Exactly, the performance of this program is not a big deal
The main purpose of my program is to find out the effect of different combinations
of different strategies, using boost::function to test those different combinations(hundred or thousand)
would be very useful and save me a lot of times

Though boost::any is icky

?Why, overhead is too high?Never try it before
boost::any makes you write code like this everywhere (unless you want to ignore errors):

1
2
3
4
5
6
7
8
9
10
11
boost::any a( 42 ); // whatever
int* pInt = boost::any_cast<int>( a );
if( pInt )
{
    // do stuff
}
else
{
    double* pDouble = boost::any_cast<double>( a );
    if( pDouble ) // ...
}


Essentially you have to guess at what the type may be, unless you just happen to "know" what it holds, as in my example.

Thanks a lot, since I know the set of possible types at compile time I would prefer boost::variant
rather than boost::any.
In which case the best way to deal with a variant is via static_visitor and apply_visitor (NOT through boost::get<>, since that reverts back to the above code):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct variant_printer : boost::static_visitor<>
{
    explicit variant_printer( std::ostream& os ) : os( os ) {}

    template< typename T >
    result_type operator()( const T& t ) const
        { os << t << std::endl; }

    std::ostream& os;
};

boost::variant< int, double, std::string > v( "Hello world" );

boost::apply_visitor( variant_printer( std::cout ), v );


As an example.
Topic archived. No new replies allowed.