Today, I want to show the specialize of classes. Thereby, you can give a diferent implementation.
Templates are so useful but sometimes could be necessary to make exceptions. C++ provide this tool that is similar to override functions.
Testing specialitzations:
#include <iostream> //base case or primary template template <typename T1, typename T2> class Example{ private: T1 _element1; T2 _element2; public: Example(){ std::cout << "Example" << std::endl; } }; //Specializations or also called partial or full specialization //depending on each case template <typename T> class Example<T, T>{ private: int _element1; int _element2; public: Example(){ std::cout << "Example same class" << std::endl; } }; template <typename T> class Example<T, int>{ private: int _element1; int _element2; public: Example(){ std::cout << "Example template and int" << std::endl; } }; template <typename T1,typename T2> class Example<T1*,T2*>{ private: int _element1; int _element2; public: Example(){ std::cout << "Example template* and template* " << std::endl; } }; int main(){ Example<int,float> ex1; Example<float,float> ex2; Example<float,int> ex3; Example<int*,float*> ex4; //Exampleex5; // error: /* * main.cpp:57:22: error: ambiguous class template instantiation for ‘class Example<int, int>’ * main.cpp:19:20: error: candidates are: class Example<T, T> * main.cpp:31:22: error: class Example<T, int> * * To fix it we might specify: * * template <> * class Example<int,int> */ //Exampleex6; // error: /* * main.cpp:64:24: error: ambiguous class template instantiation for ‘class Example<int*, int*>’ * main.cpp:19:20: error: candidates are: class Example<T, T> * main.cpp:42:23: error: class Example<T1*, T2*> * * To solve this issue we could implement a specialitzacion for pointers * of the same type: * * template<typename T> * Example<T*, T*> * */ }
No comments:
Post a Comment