简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM