Question

I want to define interface for serializing variables, where depending on a template argument, serialization code (true) or nothing (false) is performed. The serialization function is itself templated on archive and variable types.

Is it better to partially specialize serialization function, or specialize class with static method inside? Is the code below correct? Is there a better way?


This is my pseudo-code where I am not sure, whether it would work or not.

The class-approach looks something like this:

template<bool ser>
struct MaybeSerialize;

template<> struct MaybeSerialize<true>{
   template<class ArchiveT, class T>
   static void serialize(ArchiveT& archive, T& var){ /* serialize*/ }
};

template<> struct MaybeSerialize<false>{
   template<class ArchiveT, class T>
   static void serialize(ArchiveT& archive, T& var){ /* do nothing*/ }
};

// call like this
MaybeSerialize<compileTimeBool>::serialize(archive,variable);

The partial specialization would be (the syntax is probably wrong):

template<bool ser, class Archive T, typename T> maybeSerialize(ArchiveT&,T&);
template<class ArchiveT, typename T> maybeSerialize<true>(ArchiveT&,T&){ /* serialize */ }
template<class ArchiveT, typename T> maybeSerialize<false>(ArchiveT&,T&){ /* do nothing */ }
// call like this
maybeSerialize<compileTimeBool>(archive,variable);
Was it helpful?

Solution

As Pubby already commented it's not possible to partially specialize template functions in C++, you have to go with class specialization. Nevertheless a static if implementation in C++ is pretty simple:

/**
 * Usual meta-IF
 * Chooses between two template parameters dependent on a given static
 * boolean value.
 *
 *  @tparam b The static boolean value to check
 *  @tparam T The class chosen when b yields true
 *  @tparam E The class chosen when b yields false
 */
template <bool b, class T, class E>
struct IF;

/**
 * Specialization for IF<true,T,E>. Chooses T for typedef RET.
 */
template <class T, class E>
struct IF<true,T,E> {
   typedef T RET;
};

/**
 * Specialization for IF<false,T,E>. Chooses E for typedef RET.
 */
template <class T, class E>
struct IF<false,T,E> {
   typedef E RET;
};

(Code taken from Static interfaces in C++, Brian McNamara and Yannis Smaragdakis)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top