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

前端 未结 4 1293
青春惊慌失措
青春惊慌失措 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:30

    You can provide a specialization for only that function outside the class declaration.

    template  struct Node
    {
        // general method split
        void split()
        {
            // implementation here or somewhere else in header
        }
    };
    

    // prototype of function declared in cpp void splitIntNode( Node & node );

    template <>
    void Node::split()
    {
         splitIntNode( this ); // which can be implemented
    }
    
    int main(int argc, char* argv[])
    {
       Node  x;
       x.split(); //will call original method
       Node  k;
       k.split(); //will call the method for the int version
    }
    

    If splitIntNode needs access to private members, you can just pass those members into the function rather than the whole Node.

提交回复
热议问题