Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Partial Template Specialization | Template Specialization
C++ Templates
course content

Зміст курсу

C++ Templates

C++ Templates

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

book
Partial Template Specialization

Template specialization for a single-parameter template is straightforward, but it becomes more complex with multiple parameters. This is where partial template specialization comes in. It allows you to create a specialized version of a template for specific subsets of types or values.

cpp

main

copy
12345678
// What if `T1` and `T2` are the same type? // Or what if you want to define special behavior when `T1` is a `std::string`? template<typename T1, typename T2> void TemplateExample(T1 first, T2 second) { std::cout << "Generic template!" << std::endl; }

Syntax of Partial Template Specialization

You can think of partial template specialization as a form of template overloading. Here are the rules to follow:

In partial specialization, you define a new version of a template function with some of its parameters fixed to specific types while leaving others as generic. The compiler uses this specialized version whenever it encounters matching types during template instantiation.

cpp

main

copy
123456789101112131415
#include <iostream> // Primary template template<typename T1, typename T2> bool IsSameType(T1 first, T2 second) { return false; } // Partial specialization for when both types are the same template<typename T> bool IsSameType(T first, T second) { return true; } int main() { std::cout << IsSameType(10, 'a') << std::endl; std::cout << IsSameType("Hello", "World") << std::endl; }

That is one way to use template specialization, but there is another, more common scenario.

cpp

main

copy
123456789101112131415
#include <iostream> // Primary template template <typename T1, typename T2> // General case void Template(T1 a, T2 b) { std::cout << "General" << std::endl; } // Partial specialization for when `T1` is `bool` template <typename T2> // Special case when the first type is `bool` void Template(bool a, T2 b) { std::cout << "Special" << std::endl; } int main() { Template(false, 25); Template(100, 300); }
What is partial template specialization?

What is partial template specialization?

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

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

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

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

Секція 4. Розділ 3
We're sorry to hear that something went wrong. What happened?
some-alt