如果我想专门化一个模板中的一个方法,我该怎么办?

如果我想专门化一个模板中的一个方法,我该怎么办?

问题描述:

假设我有一个模板类,如

Say I have a templated class like

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

需要专注于在Triangle类案例中。

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

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

但我不要要重写整个模板!唯一需要改变的是 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.

您可以在类声明之外为该函数提供专门化。

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
    }
};

//在cpp中声明的函数原型
void splitIntNode(Node& node);

// 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
}

如果 splitIntNode 需要访问私有成员,您只需将这些成员传递到函数中,而不是整个Node。

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