1

I have this chunk of code that is a common pattern to do template specialization. To remove the requirement of specifying DataType1 for Processor1<DataType1> in the first line of main function, I want to receive a template template argument instead. Looks like the using directive does not support assigning an "open" template argument and I'm unable to find any example of that in the web (maybe I'm not searching with the appropriate keywords...)

#include <iostream>

struct DataType1 {};
struct DataType2 {};

template<class TDataType>
struct BaseMessage{ using DataType = TDataType; };

template<class TDataType>
struct ChildMessage : public BaseMessage<TDataType> {};

template<class TDataType>
struct Processor1 {
    static void func() { std::cout << "Processor1" << std::endl; }
};

template<class TDataType>
struct Processor2 {
    static void func() { std::cout << "Processor2" << std::endl; }
};

template<class TResult>
struct FindDefaultProcessor;

template<>
struct FindDefaultProcessor<DataType1>
{
    using type = Processor1;
};

template<class TResult, template<class> class TProcessor = FindDefaultProcessor<TResult>::type>
void func()
{
    TProcessor<typename TResult::DataType>::func();
}

int main()
{
    func<ChildMessage<DataType2>, Processor1>();
    return 0;
}

So the question is pretty "simple", how can I make this code compile? in FindDefaultProcessor, using type = Processor1; does not compile. I need a mechanism to retrieve a type that is still "open".

cigien
  • 57,834
  • 11
  • 73
  • 112
Sproulx
  • 314
  • 3
  • 13

1 Answers1

2

Processor1 is not a type, you probably mean

template<>
struct FindDefaultProcessor<DataType1>
{
    template <typename U>
    using type = Processor1<U>;
};

and you need extra keyword template:

template<class TResult,
         template<class> class TProcessor = FindDefaultProcessor<TResult>::template type>
                                                                           ^^^^^^^^

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Oh wow I indeed added a template but forgot to add the U to Processor1. And thank you for the fix on ::type as it requires template keyword. this syntax looks like a deep c++ secret to me :p (cannot accept the answer before 9 minutes... ok stackoverflow...) – Sproulx Mar 25 '21 at 15:17
  • 1
    @Sproulx This post https://stackoverflow.com/questions/610245 covers the need for that syntax quite nicely. – cigien Mar 25 '21 at 15:17