特化模板中的一些方法

Specializing some methods in template

我有一个 class,它有一个模板专业化版本。但是,前者看不到通用版本实现的方法。 我怎样才能使通用版本中的所有方法都可见 专业版?

例如:

test.hpp

#include <iostream>

template <typename T>
class A_base{
public:
    virtual void foo() = 0;
};

template <typename T>
class A : public A_base<T> {
public:
    void foo() override {
        std::cout << "foo: generic type" << "\n";
    }
};

template <>
class A<int> : public A_base<int>{
public:
    void bar() {
        std::cout << "bar: int type" << "\n";
    }
};

test.cpp

#include "test.hpp"

int main(){
    A<int> a;
    a.foo(); // expected "foo: generic type"
    a.bar(); // expected "bar: int type"
}

为什么A<int> a看不到foo()

Why A<int> a can't see foo()?

通过为 T = int 专门化 class 模板 A<T>,您定义了 class 模板 A<T>T 对应时的方式到 int,并且您提供的那个专业化(即:A<int>)有 没有 成员称为 foo(但是主模板确实如此)。

可以单独特化 class 模板的成员函数。因此,您可以简单地将 class 模板 T 的成员函数 bar 专门化为 T = int,而不是为整个 class 模板专门化:

template <>
void A<int>::bar(){
        std::cout << "bar: int type" << "\n";
}