Question

In following code, I got an compiling error

#include <iostream>

using namespace std;

template <typename T, int I>
class MyClass {
public:
    void func1(){
    cout<<"default: func1"<<endl;
    }
    void func2(){
    cout<<"default: func2"<<endl;
    }
private:
    T haha;
};

template <typename T>
void MyClass<T, 1>::func1(){
    cout<<"special: func1"<<endl;
};



int main()
{
    MyClass<int, 2> intclass;
    intclass.func1();
    intclass.func2();

    MyClass<double, 1> doubleclass;
    doubleclass.func1();
    doubleclass.func2();
    return 0;
}

I got following compiling error:

partialspecifizednontype.cpp:19: error: invalid use of incomplete type 'class MyClass<T, 1>'
partialspecifizednontype.cpp:6: error: declaration of 'class MyClass<T, 1>'

Any specific reason that I can't do this? Is there any workaround to achieve this?

I notice that if my template class don't have first parameter things are OK. (my gcc is 4.2.1)

Following example is OK:

#include <iostream>

using namespace std;

template <int I>
class MyClass {
public:
    void func1(){
    cout<<"default: func1"<<endl;
    }
    void func2(){
    cout<<"default: func2"<<endl;
    }
};

template<>
void MyClass<1>::func1(){
    cout<<"special: func1"<<endl;
};



int main()
{
    MyClass<2> intclass;
    intclass.func1();
    intclass.func2();

    MyClass<1> doubleclass;
    doubleclass.func1();
    doubleclass.func2();
    return 0;
}
Was it helpful?

Solution

Member functions of class templates are also function templates in their own right. That means that you can specialize them explicitly (as you do in your second example), but function templates cannot be specialized partially (as you are trying in your first example).

As a workaround, you can specialize the entire class partially:

template <typename T>
class MyClass<T, 1>
{
public:
    void func1() { cout << "special: func1" << endl; };
    // ...
};

You may need to refactor your code to put common code into a base class to make this approach maintainable.

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