Templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
/* Template Function. 'template <class T>' or 'template <typename T>' | |
can be used here.*/ | |
template <class T> | |
void exampleFunction(T val) { | |
cout << val; | |
} | |
/* Template Class. 'template <class T>' or 'template <typename T>' | |
can be used here.*/ | |
template <class T> | |
class ExampleClass { | |
T memberVariable; | |
public: | |
ExampleClass(T val) :memberVariable(val) {} | |
void printMemberVaraible() { | |
cout << memberVariable; | |
} | |
}; | |
int main() { | |
exampleFunction(5); //correct | |
exampleFunction<int>(5); //correct. 'int' type passed as template argument is optional; | |
ExampleClass ec1(4); //incorrect. 'int' Type needs to passed as a template argument. | |
ExampleClass<int> ec1(4);//correct | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment