C++ Generic Types

Posted on December 12, 2013. Filed under: C++ | Tags: |


generic type

generic function

In a nutshell, generics enable types (classes) to be parameters when defining classes and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
The c++ keyword for generic is “template”:
#include
using namespace std;
template
T add(S a, U b, V c) {
return a+b+c;
}
int main() {
int x=1, y=2, z=3, s;
s=add(x,y,z);
cout<<s<<endl;
double x=1.00, y=2.00, z=3.00;
int s;
s=add(x,y,z);
cout<<s<<endl;
}

Generic types çan also be passed into class with < >, for example:

Bucky <int> bo(256, 105);

#include <iostream>

using namespace std;

template <class T>

class Bucky{

T first, second;

public:

Bucky(T a, S b){

first =a;

second=b;

}

T bigger();

};

template <class T>  //define function outside of class

T Bucky<T>::bigger(){

return (first>second?first:second);

}

int main() {

Bucky <int> bo(256, 105); //pass type variable to class constructor

cout<<bo.bigger():

}

Now the class have generic implementation for generic types, however, we still want to do the opposite, we want to have a specific implementation for a specific class type, we can do that by declare template specializations with “template<>”

#include <iostream>

using namespace std;

template <class T>

class Spunky{

public:

Spunky(T x) {

bout << x << ” is not a character” << endl;

}

};

template<>   //declare template specialization

class Spunky<char>{

public:

Spunky(char x){

count << x<< ” is indeed a character” << endl;

}

};

int main() {

Spunky <int> obj1(7);

Spunky <char>obj3(‘q’);

}

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: