[CPP] Template classes and functors
Template classes
In the last blog, we introduce template functions:
Also, we can make a template class, which is similar to generic class in Java.
- Here is a simple version of linked list to store integer value
- Let’s now using template to make it to store all kinds of data
- Add prior to each member function definition: template < typename T>
- Add the < T >to the end of the class name in the member function implementation/definition(if we have separate .h and .cpp file)
- Still remember we use it in STL containers:
vector<int> vector1;
Functors
Simple functors
functors are classes which overload () operator
Functors with member data
Functors taking variables by reference
Functors vs Functions
Here, what we did is to use a function pointer and apply function using this function pointer.
But now i want to make the function pointer to functors or make it to use both, what should i do?
- Use Template!
What we do here?!
Because function pointer and functor both use () operator, so it will work on both. Also, template is really nice and brilliant on this!
Also, functors are object, they behave like function but it is not a function! The most important thing about them is that they can store things in themselves
Another advanced way
- < functional> header file
- std::function< return type (param types) > function name
- Template class, type specifies return type and parameters
- Store, copy or invoke any callable of correct type, for example function pointer and functors
- Useful if you need to store these things for calling later
评论
发表评论