+ 2

Need your help with class template syntax.

Can't figure out what I am missing. HEADER: #pragma once template <class T> class Pair { private: T first, second; public: Pair(T a, T b); T bigger(); ~Pair(); }; SOURCE: #include "stdafx.h" #include "Pair.h" template <class T> Pair::Pair(T a, T b) :first(a), secon(b) { } T Pair<T>::bigger() { return (first > second ? first : second); } Pair::~Pair() { } MAIN: #include "stdafx.h" #include <iostream> #include "Pair.h" using namespace std; int main() { Pair <int> obj(11,22); cout << obj.bigger() << endl; return 0; } Would appreciate any help.

28th Feb 2017, 3:28 PM
Arthur Fedotiev
Arthur Fedotiev - avatar
5 Réponses
+ 1
you can not declare template functions, methods, variables ... in your source file, they have to be in the header file
28th Feb 2017, 3:59 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
You need to implement all your templates in the header file and everything should be fine :) (if there are no other bug)
1st Mar 2017, 6:21 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
Baptiste E. Prunier, it has worked, thanks a lot. Though it still seem ridiculouc for me to implement them in the header when we have source. In addition to that one of the lessons is confusing me saying following: "A specific syntax is required in case you define your member functions outside of your class - for example in a separate source file. You need to specify the generic type in angle brackets after the class name. For example, to have a member function bigger() defined outside of the class, the following syntax is used: template <class T> class Pair { private: T first, second; public: Pair (T a, T b): first(a), second(b){ } T bigger(); }; template <class T> T Pair<T>::bigger() { // some code } "
1st Mar 2017, 6:58 AM
Arthur Fedotiev
Arthur Fedotiev - avatar
+ 1
My pleasure ! It was also for me in the beginning but it is because even if you write code, they are not really implemented. When you'll compile your code, each version of the class you'll need will be implemented with its specific type
1st Mar 2017, 7:02 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
@Baptiste E. Prunier, do you mean that I need just to remove line "template <class T>" from the source file or to include implementation of the function that use generic data type into the header? I don't understand it at all :(
28th Feb 2017, 7:52 PM
Arthur Fedotiev
Arthur Fedotiev - avatar