Search code examples
c++templatessimplification

Template simplification


In one of my projects, I have the following class template hierarchy :

template <typename FruitType, typename ParentFilterType = void>
class filter;

template <typename FruitType> // Specialization when no parent filter is needed
class filter<FruitType, void>;

Where FruitType can be anything. Let's say it is one of apple, banana or orange. So basically, a filter can have its own parent filter type.

I have no control over the filter code: it must remain as it is.

The user code usually looks like:

filter<apple, filter<banana, filter<orange> > > my_apple_filter;

Obviously, this is a bit verbose. I wondered if it is possible to get something more readable. Something like:

complex_filter<apple, banana, orange>::type my_apple_filter;

Where complex_filter<apple, banana, orange>::type would resolve to filter<apple, filter<banana, filter<orange> > >.

I tried with complex_filter being a struct template with a typedef inside but had no success so far. The number of template parameters should be variable (from, say, 1 to 5).

Have you ever needed something similar ? How could I do that ?

(I unfortunately cannot use C++0x but if there is a nicer solution with it, feel free to post it as it is always good to know)

Thank you.


Solution

  • In C++0x, it would be variadic template.

    Without C++0x, you can simply use a large list of parameters, with defaults supplied.

    template <typename F0, typename F1 = void, typename F2 = void, typename F3 = void>
    struct complex_filter
    {
      typedef filter<F0, typename complex_filter<F1, F2, F3>::type> type;
    };
    
    template <>
    struct complex_filter<void,void,void,void>
    {
      typedef void type;
    };
    

    This can then be used as you wanted, and you will have to extend it manually if you ever want more parameters.