Skip to content

Instantly share code, notes, and snippets.

@sjhalayka
Created February 21, 2025 17:31
Show Gist options
  • Save sjhalayka/eb33261bde4774e171e193a44d635cac to your computer and use it in GitHub Desktop.
Save sjhalayka/eb33261bde4774e171e193a44d635cac to your computer and use it in GitHub Desktop.
C++ template usage examples
#include <iostream>
#include <vector>
using namespace std;
// C way -- make one function for each type
double c_function(const double x)
{
return x;
}
char c_function2(const char x)
{
return x;
}
// C++ way -- make only one function for all types
template<class T> // T is the type that is dealt with in the function
T cpp_function(const T x)
{
return x;
}
int main(void)
{
// Example 1:
// Reduce code complexity by using templates
// Note that in C, we would need two functions, one per type
double a = c_function(123.4);
char b = c_function2(' ');
// Note that in C++, we only need one function, for all types
double c = cpp_function<double>(123.4);
double d = cpp_function<char>('*');
// Example 2:
// To allocate a contiguous block of memory in C++, use the vector.
// The vector accepts a template parameter which tells us what type
// is stored in the vector
vector<double> e; // Make a vector of doubles
e.resize(9876); // Make the block of memory big enough to store 9876 elements
e[0] = 6.1; // Use brackets to access the first element, like in C
vector<char> f; // Make a vector of chars
f.resize(9876); // Make the block of memory big enough to store 9876 elements
f[f.size() - 1] = ' '; // Use brackets to access the last element, like in C
// Note that the vector's internal memory is automatically
// released when it goes out of scope here
// This is why we prefer vector over malloc/new[] and free/delete[]
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment