How to parameterize a function according to a function template?

When implementing the byte order conversion function for a structure, I found that the implementation violates the DRY principle.
Here is a code snippet to show what I mean:

inline void FromHostByteorderToNetwork(ServerStatus& ss) { ss.field0 = qToBigEndian<__int32>(ss.field0); ss.field1 = qToBigEndian<__int16>(ss.field1); //... 20+ more fields assigned in the same way inline void FromNetworkByteorderToHost(ServerStatus& ss) { ss.field0 = qFromBigEndian<__int32>(ss.field0); ss.field1 = qFromBigEndian<__int16>(ss.field1); //... 20+ more fields assigned in the same way 

What I need: one subroutine where I can pass the name of the template function (qToBigEndian / qFromBigEndian), with an implementation like:

 template <typename ByteConversionFunctionT> inline void changeByteOrder(ServerStatus& ss) { ss.field0 = ByteConversionFunctionT<__int32>(ss.field0); ss.field1 = ByteConversionFunctionT<__int16>(ss.field1); 

Important information:
Also note that the ByteConversionFunctionT inside changeByteOrder is created using another type: for example, __int32 / __ int16

in the headers of Qt qFrom / To is a template:

 template <typename T> inline T qFromBigEndian(T source) 

Can you suggest a way to do this, or perhaps obey KISS and duplicate code to avoid extra complexity?

+7
c ++ templates
source share
1 answer

One option is to write a template template shell:

 template <class T> struct FromBigEndian { static T call(T source) { return qFromBigEndian(source); } }; template <class T> struct ToBigEndian { static T call(T source) { return qToBigEndian(source); } }; template <template <class> class ByteConvertor> void changeByteOrder(ServerStatus &ss) { ss.field0 = ByteConvertor<__int32>::call(ss.field0); ss.field1 = ByteConvertor<__int16>::call(ss1.field1); } 
+6
source share

All Articles