You have two classic possibilities.
First, use two global function overloads, one for ComponentDc , one for ComponentIc :
void globalExec(ComponentDc) { std::cout << "Hello"; } void globalExec(ComponentIc) { std::cout << "World"; } void Device<Component>::exec() { globalExec(Component); }
Secondly, use a feature class: a clean template class with no fields and with different typedefs and only static functions as methods. This class has its own specializations for various possible types of arguments.
template<Component> class DeviceTraits {}; template<> class DeviceTraits<ComponentDc> { static std::string getMessage() { return "Hello"; } }; template<> class DeviceTraits<ComponentIc> { static std::string getMessage() { return "World"; } }; void Device<Component>::exec() { std::cout << DeviceTraits<Component>::getMessage(); }
The advantage of using feature classes is that you do not need to spoil your global namespace with multiple functions.
The partial specialization of the Device class itself is not always possible, and it is considered more convenient to move any code depending on the template to the feature class.
This is the classic approach used in STL. Alternatively, you can use boost::enable_if or std::enable_if (for the latest compilers).
source share