C++ template class specialization: why do common methods need to be re-implemented

Jaime picture Jaime · Jan 9, 2012 · Viewed 10.2k times · Source

In the sample:

#include <iostream>

using namespace std;

class B
{
public:
    virtual void pvf() = 0;
};

template <class T>
class D : public B
{
public:
    D(){}

    virtual void pvf() {}

private:
    string data;
};

template <>
class D<bool> : public B
{
public:
    D();

    virtual void pvf(){ cout << "bool type" << endl; }
};

int main()
{
    D<int> d1;
    D<bool> d2;
}

I get the following error:

test.cpp:(.text+0x1c): undefined reference to `D<bool>::D()'

Note that the reason I don't just specialize the D() by itself is I want to eliminate the need for string D<T>::data in the D<bool> case.

Why do I need to re-implement D() in D<bool>? Seems like there should be a way for me to tell the compiler to use the version from D<T>.

Is there any way to do a simple specialization like this without having to re-implement methods?

Answer

Mike Seymour picture Mike Seymour · Jan 9, 2012

Each specialisation of a class template gives a different class - they do not share any members with each other. Since you've explicitly specialised the entire class, you don't get any of the members from the template, and must implement them all.

You can explicitly specialise individual members, rather than the entire class:

template <> void D<bool>::pvf(){ cout << "bool type" << endl; }

Then D<bool> will still contain all the members of the class template that you haven't explicitly specialised, including the default constructor.