Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

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.

like image 408
bobobobo Avatar asked Feb 17 '12 15:02

bobobobo


People also ask

What is template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

When we specialize a function template it is called?

To do so, we can use a function template specialization (sometimes called a full or explicit function template specialization) to create a specialized version of the print() function for type double.

What is the specialty of a template function give example?

Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type.

Are template specializations inline?

An explicit specialization of a function template is inline only if it is declared with the inline specifier (or defined as deleted), it doesn't matter if the primary template is inline.


1 Answers

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.

like image 109
Luchian Grigore Avatar answered Sep 21 '22 17:09

Luchian Grigore