Course Content
C++ Templates
C++ Templates
Implicit and Explicit Type Specification
Implicit type specification
In most cases, the C++ compiler can automatically determine the template type from the arguments passed to the function. If the parameter types provide all the information needed, there's no need to specify the type explicitly.
main
#include <iostream> template<typename T> void PrintValue(T value) { std::cout << value << std::endl; } // The compiler assigns the type for `T` // Based on the type of the passed argument `value` int main() { PrintValue(42); // `T` is deduced as `int` PrintValue(3.14); // `T` is deduced as `double` PrintValue("Hello"); // `T` is deduced as `const char*` }
The compiler automatically determines the type of the template parameter T
based on the function arguments. This makes the function calls more concise and easier to read. For this reason you might actually already used templates without realising it.
main
header
#include <iostream> int main() { int a = 300; int b = 200; // `std::swap` is actually a template and you can prove it // Try to specify `int` type explicitly `std::swap<int>` std::swap(a, b); std::cout << a << " " << b << std::endl; }
Explicit type specification
With all of that, a question arises: If type deduction is implicit, why bother specifying the type explicitly? This is because there are scenarios where automatic type deduction doesn’t work or isn’t sufficient, requiring you to specify the template type explicitly. Take a look at an examples.
ambiguous
forcing_type
no_parameters
#include <iostream> template<typename T> T GetDefaultValueSum(T a, T b) { return a + b; } int main() { // If `float` won't be specified, this code would generate an error std::cout << GetDefaultValueSum<float>(2, 2.5) << std::endl; }
Thanks for your feedback!