0

I have a template member function inside template class, this works OK, it looks like the one in the below question.

Template function inside template class

#include <iostream>

using namespace std;

template <class T>
class MyClass {
public:
    template <class U>
    void foo();
};

template <class T>
template <class U>
void MyClass<T>::foo() {
    cout << "foo" << endl;
}

int main()
{
    MyClass<int> a;
    a.foo<double>();
    return 0;
}

But what if I would like to specialize the template member function foo?

So, I try to add this member function specialization, but it get compile failure.

template <class T>
template <>
void MyClass<T>::foo<double>() {
    cout << "special foo for double" << endl;
}

Any idea on how to fix this issue? Thanks.

ollydbg23
  • 1,124
  • 1
  • 12
  • 38
  • You have to specialize the class also. You can't just specialize the member function(without specializing the class). – Jason Jan 21 '23 at 11:43
  • https://stackoverflow.com/a/68150661/154911 I think this answer also solves my question. Thanks. – ollydbg23 Jan 21 '23 at 14:56

0 Answers0