Template specialization and inheritance

后端 未结 3 919
北荒
北荒 2021-02-01 04:21

Suppose I have a template class with a lot of functions and I want to specialize them to change only a few of them and keep the other ones exactly as specified in the base templ

相关标签:
3条回答
  • 2021-02-01 04:57

    You just have to use two template classes:

    template<typename T>
    struct CommonBase
    {
      void print1() {cout << "Base::print1" << endl;};
      void print2() {cout << "Base::print2" << endl;};
    };
    
    template<typename T>
    struct Base : public CommonBase<T>
    {
    };
    
    template<>
    struct Base<int> : public CommonBase<int>
    {
      void print2() {cout << "Base::print2" << endl;};
    };
    

    You always use Base, rather than CommonBase.

    0 讨论(0)
  • 2021-02-01 05:04

    Nicol's solution works fine, but this is an alternative:

    template<typename T>
    struct Base
    {
      void print1() {cout << "Base::print1" << endl;};
      void print2() {cout << "Base::print2" << endl;};
    };
    
    template<>
    void Base<int>::print2() {cout << "Base<int>::print2()" << endl;};
    

    That way you can specialize only specific member functions and still use those that you haven't specialized(in this case, print1) without any problem. So now you'd use it just like you wanted:

    Base<int> i;
    i.print1();
    i.print2(); // calls your specialization
    

    Demo here.

    0 讨论(0)
  • 2021-02-01 05:09

    Another solution would be to add a level of indirection in the function you want to redefine, i.e.

    template<typename T>
    struct foo
    {
        template<typename T2>
        void bar_impl()
        {
            //generic function
        }
    
        void bar()
        {
            bar_impl<T>();
        }
    };
    

    Then you can specialize each function individually for each type or specialize the whole type as wanted.

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