0

templates c++

hey guys i have a noob question about templates. if i define my member function of a class outside of it and i use a template why cant i use any data type i want anymore? ex: template <class T> T Pair<T>::bigger()//bigger is a function which returns the bigger value main(){ Pair <T> obj(11, 22);// compiler doesnt like it }

17th Feb 2019, 8:57 AM
sina
sina - avatar
1 Réponse
+ 4
The compiler complains because T is not a valid type, and could not be deduced. In main, if you are using an older C++ compiler, you need to pass the type of the arguments you are passing to your constructor, or the type you require for use later, in case of a default constructor. Eg: Pair<int> ob(3,4); This is why we use templates in the first place. To substitute the general type T with a type of our preference as per our need. In a compiler supporting C++17, you no longer need to pass the type in angle brackets, as the compiler can now deduce it for you, using a feature called Class Template Argument Deduction (CTAD). Eg : Pair ob(3,4); // ob is a Pair<int>.
17th Feb 2019, 11:31 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar