Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

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

Say I have a templated class like

template <typename T> struct Node
{
    // general method split
    void split()
    {
        // ... actual code here (not empty)
    }
};

Need to specialise this in the Triangle class case.. something like

template <>
struct Node <Triangle*>
{
    // specialise the split method
    void split() {}
} ;

but I don't want to rewrite the entire template over again! The only thing that needs to change is the split() method, nothing more.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

template <typename T> 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<int>::split()
{
     splitIntNode( this ); // which can be implemented
}

int main(int argc, char* argv[])
{
   Node <char> x;
   x.split(); //will call original method
   Node <int> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...