首页 > 解决方案 > 类模板的模板方法重载解析规则

问题描述

我无法理解在类模板中定义的模板方法的以下重载解决方案。

///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();
}

输出:

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

如果我评论以下代码(在类定义之外):

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

然后输出变为:

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

我的问题是,即使具有相同的函数签名,为什么在类之外定义的方法被优先考虑而没有任何冲突?如果我错误地错过了某些东西,请告诉我。

谢谢!

标签: c++templates

解决方案


这里没有重载解决方案;您专门化了成员函数模板,这就是您要求的T= int


推荐阅读