c++boostboost-bindc++98boost-function

Shortening boost::function


When passing a boost::function as a parameter to another function (callback), this function's signature can become quite long.

Example:
Consider this boost::function:

boost::function<MyClass * (
      TypeA param1,
      TypeB param2,
      TypeC param3,
      TypeD param4,
      TypeE param5,
      TypeF param6)> CreateMyClass;

Now if we pass this boost::function as a function parameter, the signature, of the function using it, becomes horribly long and hard to read:

void myFunctionUsingTheCallack(boost::function<MyClass * (
          TypeA param1,
          TypeB param2,
          TypeC param3,
          TypeD param4,
          TypeE param5,
          TypeF param6)> the_callback);

Am I missing something here? Is there any trick to shorten the signature of myFunctionWithTheCallack?


Solution

  • Why don't you typedef to a shorter name?

    typedef boost::function<MyClass * (
      TypeA param1,
      TypeB param2,
      TypeC param3,
      TypeD param4,
      TypeE param5,
      TypeF param6)> Fun;
    
    Fun CreateMyClass;
    
    void myFunctionUsingTheCallack(Fun the_callback);
    

    If you were using C++11 or above, you could use using instead of typedef:

    using Fun = boost::function<MyClass * (
      TypeA param1,
      TypeB param2,
      TypeC param3,
      TypeD param4,
      TypeE param5,
      TypeF param6)>;
    

    Instead of explicitly specifying the type you could also use a function template and let the type be deduced by the compiler:

    template <typename Fun>
    void myFunctionUsingTheCallack(Fun the_callback);