Home > Net >  How do i create a template function definition with a template class as input
How do i create a template function definition with a template class as input

Time:11-10

Say I have the following classes:

/* Frame.hpp */
template<class PayloadType>
class Frame {
    int address;
    PayloadType payload;
}
/* RequestPacket.hpp */
template<class PayloadType>
class RequestPacket { // Also a similar ResponsePacket exists
    Command command; // Command is an enum
    PayloadType payload;
}

/* GetMeanTemperatureRequest.hpp */
class GetMeanTemperatureRequest { // Many different Requests and Responses
    Period period; // Again, Period is an enum
}

And I have the following function:

/* Serializer.hpp */
template<class From, To>
size_t Serializer::serializeTo(const From& input, To buffer);

Then I would like to instantiate this function for, lets say Frame:

/* Frame.cpp */
#include "Serializer.hpp"
template<class PayloadType> // These 2 lines are the
template<>                  // subject of my question
size_t Serializer::serializeTo(const Frame<PayloadType>& input, uint8_t* buffer) {
  // implementation
}

Then I will get error: too many template-parameter-lists.

If I remove template<> then I'll get error: prototype for std::size_t Serializer::serializeTo(const Frame<PayloadType>&, uint8_t*) does not match any in class Serializer

If I change the two template<...>s around it doesn't help either

What does the compiler want?

CodePudding user response:

A specialization needs to match the primary declaration. In your primary declaration you have:

template<class From, To>
size_t Serializer::serializeTo(const From& input, To buffer);

so your specialization needs to be in the form of

template<>
size_t Serializer::serializeTo(const concrete_from_type& input, concrete_to_type buffer);

What you are doing is trying combine a specialization with another template to try and get a partial specialization but that is not allowed. What you can do instead is just add another overload of your function like

template<class PayloadType, To>
size_t Serializer::serializeTo(const Frame<PayloadType>& input, To buffer);
  • Related