If I want to specialise just one method in a template, how do I do it?

前端 未结 4 1294
青春惊慌失措
青春惊慌失措 2020-11-30 09:54

Say I have a templated class like

template  struct Node
{
    // general method split
    void split()
    {
        // ... actual code her         


        
4条回答
  •  失恋的感觉
    2020-11-30 10:28

    Awkward method that I usually use: Declare a "basic" template implementation. Then declare your template implementation, the default implementation would just inherit the "basic" one. The customize would inherit the "basic", plus override specific methods. Like this:

    template  struct NodeBase
    {
        // methods
    };
    
    template  struct Node
        :public NodeBase
    {
        // nothing is changed
    };
    
    template <> struct Node
        :public NodeBase
    {
        // re-define methods you want
    };
    

    Note that the "method overriding" has nothing to do with virtual functions or etc. It's just a declaring a function with the same name and parameters as in the base - the compiler will automatically use it.

提交回复
热议问题