3

See following code. The first MyClass<> has two functions (func1 and func2). Then I would like to do some special thing for MyClass in func1 but not func2. It looks like I have to type code for func2 again. I am wondering if there is a way to work this around? Thanks

#include <iostream>

using namespace std;

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

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

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

    MyClass<double> doubleclass;
    doubleclass.func1();
    doubleclass.func2();  // error 'class MyClass<double>' has no member named 'func2'
    return 0;
}
Yan Zhu
  • 4,036
  • 3
  • 21
  • 37

1 Answers1

6

There is no need to provide a specialization for the whole class. You can specialize that specific member function:

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

Live demo here.

mfontanini
  • 21,410
  • 4
  • 65
  • 73
  • Thanks. it works for this example. But in my working case, the template part will be used to build a static library first, then compiler will complaint about the duplicated definition. Any more comment? – Yan Zhu May 31 '13 at 23:13
  • @YanZhu make the specialization `inline`. – mfontanini May 31 '13 at 23:30
  • Thanks. It passes the linking. Any theory behind this? Could you please point some article for this? I tried google, but can't find any useful stuff. – Yan Zhu May 31 '13 at 23:55
  • @YanZhu sure, have a look at [this thread](http://stackoverflow.com/questions/4193639/inline-function-linkage). – mfontanini Jun 01 '13 at 00:22