如何仅专门化模板类的某些成员? [英] How to specialize only some members of a template class?

查看:145
本文介绍了如何仅专门化模板类的某些成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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!

推荐答案

考虑将公共部分移动到基类:

Consider moving common parts to a base class:

template <typename T>
struct ABase
{
    void f1();
};


template <typename T>
struct A : ABase<T>
{
    void f2();
}  


template <>
struct A<int> : ABase<int>
{
    void f2();
};

您甚至可以在导出的 f1 类。如果你想做更多的事情(包括能够从基类中的 f1 代码中调用 f2 请查看 CRTP

You can even override f1 in the derived class. If you want to do something more fancy (including being able to call f2 from f1 code in the base class), look at the CRTP.

这篇关于如何仅专门化模板类的某些成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆