如何仅特化模板类的某些成员?
代码:
template<class T>
struct A {
void f1() {};
void f2() {};
};
template<>
struct A<int> {
void f2() {};
};
int main() {
A<int> data;
data.f1();
data.f2();
};
错误:
test.cpp: In function 'int main()':
test.cpp:16: error: 'struct A<int>' has no member named 'f1'
基本上,我只想专门化一个函数并使用其他函数的通用定义。 (在实际代码中,我有很多我不想专门研究的函数)。
如何做到这一点?谢谢!
Code:
template<class T>
struct A {
void f1() {};
void f2() {};
};
template<>
struct A<int> {
void f2() {};
};
int main() {
A<int> data;
data.f1();
data.f2();
};
ERROR:
test.cpp: In function 'int main()':
test.cpp:16: error: 'struct A<int>' has no member named 'f1'
Basically, I only want to specialize one function and use the common definition for other functions. (In actual code, I have many functions which I don't want to specialize).
How to do this? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这会有所帮助吗:
Would this help:
考虑将公共部分移至基类:
您甚至可以在派生类中重写
f1
。如果您想做一些更奇特的事情(包括能够从基类中的f1
代码调用f2
),请查看 CRTP。Consider moving common parts to a base class:
You can even override
f1
in the derived class. If you want to do something more fancy (including being able to callf2
fromf1
code in the base class), look at the CRTP.当我们声明模板类的特化时,我们还必须定义它的所有成员,甚至是那些与通用模板类完全相同的成员,因为没有从通用模板到特化的成员继承。因此,在您的专业化中,您也必须实现
void f1();
。When we declare specializations for a template class, we must also define all its members, even those exactly equal to the generic template class, because there is no inheritance of members from the generic template to the specialization. So, in your specialization you have to implement
void f1();
too.