Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle default value for a templated functor

Given a function like this:

template<typename functor>
void foo(functor const& f)
{
    if (f)
        f(1, 2);
}

I want to be able to assign a default value where f can be set to something similar to NULL. Also, it would be possible sufficient to make a bogus call to an empty function. Is there anything I can use (from the standard or boost-library) without creating such a thing by myself?

like image 292
0xbadf00d Avatar asked Dec 02 '22 01:12

0xbadf00d


2 Answers

Use an empty functor and use as default template parameter. You can't use something like NULL because you have no pointer:

class X
{
    void operator()(...) {}
};

template <typename functor = X>
void foo(functor const& f = X())
{
    f(...);
}
like image 57
Tio Pepe Avatar answered Dec 14 '22 22:12

Tio Pepe


Either write an overload that takes and does nothing, or pass a no-op functor to foo.

like image 40
Lightness Races in Orbit Avatar answered Dec 14 '22 23:12

Lightness Races in Orbit