Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Implicit and Explicit Type Specification | Templates Usage
C++ Templates
course content

Зміст курсу

C++ Templates

C++ Templates

1. Creating First Template
2. Templates Usage
3. Class Templates
4. Template Specialization

bookImplicit 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.

cpp

main

copy
12345678910111213
#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.

cpp

main

h

header

copy
123456789101112
#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.

cpp

ambiguous

cpp

forcing_type

cpp

no_parameters

copy
12345678910
#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; }
What is the **wrong** option to replace the placeholder `___` in the following code?

What is the wrong option to replace the placeholder ___ in the following code?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 2
some-alt