Last active
May 7, 2022 17:54
-
-
Save gabrieleboccarusso/6bcb4d36f223a39260fcfec5e0d31393 to your computer and use it in GitHub Desktop.
quick snippet about cpp's 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> | |
float division (float a, float b) { | |
return a / b; | |
} | |
template <class generic> | |
generic generic_division (generic a, generic b) { | |
return a / b; | |
} | |
template <class generic, int m = 10> | |
generic multiplier (generic number) { | |
return number * m; | |
} | |
int main() { | |
std::cout << "division using a traditional function: " << division(4.5, 1.1) << std::endl; | |
std::cout << "int division using template function: " << generic_division<int>(9, 4) << std::endl; | |
std::cout << "float division using the same function: " << generic_division<float>(4.2, 1.55) << std::endl; | |
std::cout << "\n\n"; | |
// using function overloads | |
std::cout << "float division using the overloads: " << generic_division(3.8, 2.95) << std::endl; | |
std::cout << "int division using the overloads: " << generic_division(4, 2) << std::endl; | |
std::cout << "\n\n"; | |
// using and changing default templates parameters | |
std::cout << "using default parameter: " <<multiplier<int>(10) << std::endl; | |
std::cout << "using different parameter: " <<multiplier<int, 11>(5); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment