template method overload resolution rule of class template

Viewed 50

I am not able to understand the following overload resolution of a template method defined inside a class template.

///g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
#include <iostream>

#if defined(_MSC_VER)
#define PrinF   std::cout << __FUNCSIG__ <<" "<< __LINE__ << std::endl;
#else
#define PrinF   std::cout << __PRETTY_FUNCTION__<<" "<< __LINE__ << std::endl;
#endif

template<typename T>
class Apple {
public: 
    template<typename R>
    void func(const R& r) {
        PrinF;
    }

    void something() {
        func(*this);
    }
};

template<>
template<typename R>
void Apple<int>::func(const R& r) {
    PrinF;
}

int main() {
    Apple<int> a;
    a.something();
}

Output:

void Apple<T>::func(const R&) [with R = Apple<int>; T = int] 25

If I comment the following code (outside of class definition):

template<>
template<typename R>
void Apple<int>::func(const R& r) {
    PrinF;
}

Then the output becomes:

void Apple<T>::func(const R&) [with R = Apple<int>; T = int] 14

My question is, even if with the same function signature, why the method defined outside of the class is prioritized without any conflicts? Please let me know if I have missed something by mistake.

Thanks!

1 Answers

There’s no overload resolution here; you specialized the member function template, and so that’s what you call for T=int.

Related