Specializing Members but Not the Class

Rather than specializing the whole template, we can specialize just specific member function(s). For example, if Foo is a template class with a member Bar, we can specialize just that member:

template <typename T> struct Foo {    Foo(const T &t = T()): mem(t) { }    void Bar() { /* ... */ }    T mem;    // other members of Foo};template<>           // we're specializing a templatevoid Foo<int>::Bar() // we're specializing the Bar member of Foo<int>{     // do whatever specialized processing that applies to ints}

Here we are specializing just one member of the Foo<int> class. The other members of Foo<int> will be supplied by the Foo template:

Foo<string> fs;  // instantiates Foo<string>::Foo()fs.Bar();        // ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.