Search code examples
c++templatesfunctorstrategy-pattern

Functor class doing work in constructor


I'm using C++ templates to pass in Strategy functors to change my function's behavior. It works fine. The functor I pass is a stateless class with no storage and it just overloads the () operator in the classic functor way.

template <typename Operation> int foo(int a) 
{
int b=Operation()(a);
/* use b here, etc */
}

I do this often, and it works well, and often I'm making templates with 6 or 7 templated functors passed in!

However I worry both about code elegance and also efficiency. The functor is stateless so I assume the Operation() constructor is free and the evaluation of the functor is just as efficient as an inlined function, but like all C++ programmers I always have some nagging doubt.

My second question is whether I could use an alternate functor approach.. one that does not override the () operator, but does everything in the constructor as a side effect! Something like:

struct Operation {
  Operation(int a, int &b) { b=a*a; }
};
template <typename Operation> int foo(int a) 
 {
   int b;
   Operation(a,b);
    /* use b here, etc */
 }

I've never seen anyone use a constructor as the "work" of a functor, but it seems like it should work. Is there any advantage? Any disadvantage? I do like the removal of the strange doubled parenthesis "Operator()(a)" , but that's likely just aesthetic.


Solution

  • Any disadvantage?

    • Ctors do not return any useful value -- cannot be used in chained calls (e.g. foo(bar()).
    • They can throw.
    • Design point of view -- ctors are object creation functions, not really meant to be workhorses.