Implementing a non template method defined in a template class

前端 未结 5 844
盖世英雄少女心
盖世英雄少女心 2021-01-04 08:14

When I want to define a method declared in a template class, but that the method doesn\'t depend on the template parameters, have I to define it in the include files as :

5条回答
  •  鱼传尺愫
    2021-01-04 08:47

    Well, if the method doesn't depend on template parameter, you can only do that with inheritance AFAIK.

    The downside: more code + inheritance

    The upside: (much) less code generated, depending on what parts of your code actually are template dependent. In the below example, method NonDependentMethod will only generate one assembly while DependentMethod will generate as many as there are different template parameters (just one in this case, but make a MyClass and you have two, etc).

    #include 
    using namespace std;
    
    class MyClassBase
    {
    public:
        void NonDependentMethod();
    };
    
    template  class MyClass : public MyClassBase
    {
    public:
        void DependentMethod(T param);
    };
    
    void MyClassBase::NonDependentMethod()
    {
        cout << "NonDependentMethod << endl;
    }
    
    template void MyClass::DependentMethod(T param)
    {
        cout << "DependentMethod " << param << endl;
    }
    
    int main() {
        // your code goes here
        MyClass cls;
        cls.NonDependentMethod();
        cls.DependentMethod(2);
        return 0;
    }
    

提交回复
热议问题