Search code examples
c++templatestype-deduction

c++ template member function specialization based on parameter value


I try to simplify c++ code in quite large old c++ project solving following simple example would help me apply the pattern to the code I work with. The code is quite large And I simplified it to the core problem.

I would like to write c++ template code which can deduce template type in compile time based on argument (for example enum). In my current code I have to write template type by hand

GetSignal<int*>(Signals::Clear) 

which can be error prone. I would like to implement SomeMagicNeedToBeHere to cause the expected behaviour.

enum Signals{ Clear, Filtered};


template <class DATA> class ContainerClass 
    : public SomeMagicNeedToBeHere<int*,Signals::Clear>,
      public SomeMagicNeedToBeHere<float*,Signals::Filtered>
{
   void DoSomething()
   {
        //auto == int*
        auto clear = GetSignal(Signals::Clear);

        //auto == float*
        auto filtered = GetSignal(Signals::Filtered);

   }
};

It is possible to deduce the type based on argument value and how?

UPDATE (rewrite the example):

I have checked the old code and my example was not right, there was no base class for typed being deduced. I have changed the fruit to int and float for better understanding.


Solution

  • Something like the following may help:

    // helper to get some type depending of signal
    template <Signals sig> struct helper;
    
    // specialization for each Signal to get type
    template <>
    struct helper<Clear>
    {
        using type = int*;
    };
    
    template <>
    struct helper<Filtered>
    {
        using type = float*;
    };
    
    // And you may do similar stuff with function (and be generic if the type helper is enough)
    template <Signals sig>
    typename helper<sig>::type GetSignal()
    {
        return nullptr;
    }