How to specialize only some members of a template class?

后端 未结 3 1096
忘了有多久
忘了有多久 2020-12-29 12:44

Code:

template
struct A {
  void f1() {};
  void f2() {};

};

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


int main() {
  A<         


        
相关标签:
3条回答
  • 2020-12-29 13:01

    Would this help:

    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
    }
    
    0 讨论(0)
  • 2020-12-29 13:06

    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();
    };
    

    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.

    0 讨论(0)
  • 2020-12-29 13:21

    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.

    0 讨论(0)
提交回复
热议问题