Search code examples
c++templatestemplate-specializationpartial-specialization

C++ template specialization - specialize only some methods, using default impl for the rest


I have a template like:

template <typename T>
class MyThing {
 public:
  static void Write(T value) { ... }
  static void Flush() { ... }
}

For a specific type, eg bool, I want to specialize the Write method without modifying the other methods. Something like this...

// Specialize Write() behavior for <bool> ...
// This won't work. Mything<bool> no longer has a Flush() method!
template <>
class MyThing<bool> {
 public:
  static void Write(bool value) { ... }
}

How do I specialize just one of the methods in a template class?


Solution

  • The fix for this turns out to be simple ...

    All I need to do is to define the method in my .cc file:

    template <>
    void MyThing<bool>::Write(bool value) { ... }
    

    And then declare it in my .h file:

    template <>
    void MyThing<bool>::Write(bool value);
    

    It took me a while to figure this out, so I thought I'd post it.