我有一个具有模板特化版本的类。然而前者看不到通用版本实现的方法。 如何使通用版本中的所有方法都可见 专用版本?
例如:
测试.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";
}
};
测试.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 seefoo()
?
通过专门化类模板A<T>
对于 T = int
,您正在定义类模板 A<T>
的方式是什么时候T
对应int
,并且您提供的特化(即: A<int>
)没有名为 foo
的成员(但是主模板确实如此)。
可以单独特化类模板的成员函数。因此,您可以简单地特化成员函数 bar
类模板的T
对于 T = int
而不是对整个类模板执行此操作:
template <>
void A<int>::bar(){
std::cout << "bar: int type" << "\n";
}
关于c++ - 专门化模板中的一些方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48348093/