【问题标题】:How to specialize only some members of a template class?如何只专门化模板类的某些成员?
【发布时间】:2011-02-10 10:01:27
【问题描述】:

代码:

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'

基本上,我只想专门化一个函数,而对其他函数使用通用定义。 (在实际代码中,我有很多我不想专门化的函数。

如何做到这一点?谢谢!

【问题讨论】:

    标签: c++ templates template-specialization partial-specialization


    【解决方案1】:

    考虑将公共部分移至基类:

    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

    【讨论】:

      【解决方案2】:

      这会有帮助吗:

      template<typename T>
      struct A
      {
        void f1()
        {
          // generic implementation of f1
        }
        void f2()
        {
          // generic implementation of f2
        }
      };
      
      template<>
      void A<int>::f2()                                                               
      {
        // specific  implementation of f2
      }
      

      【讨论】:

      • 我会这样做。一个值得注意的可能性是,如果 f2() 应该为每个类型名 T 专门化,它也可以只在类中声明(未实现)。这具有编译时检查给定 T 的实现存在的额外好处(如果未实现,链接器将抱怨。)
      【解决方案3】:

      当我们为模板类声明特化时,我们还必须定义它的所有成员,即使是那些与泛型模板类完全相同的成员,因为从泛型模板到专业化。所以,在你的专业中,你也必须实现void f1();

      【讨论】:

      • 谢谢。是否有避免重复代码的解决方法/语法? (当然除了#define)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      相关资源
      最近更新 更多