Templates
Template Specialization
A specialization can give one type its own implementation while other types use the general template.
Template Specialization
template_specialization.cpp
#include <iostream>
#include <string>
template <typename T>
std::string describe(T value) {
return "value=" + std::to_string(value);
}
template <>
std::string describe<bool>(bool value) {
if (value) {
return "flag=yes";
}
return "flag=no";
}
int main() {
int score = ;
bool active = ;
std::cout << describe(score) << std::endl;
std::cout << describe(active) << std::endl;
return 0;
}
#include <iostream>
#include <string>
template <typename T>
std::string describe(T value) {
return "value=" + std::to_string(value);
}
template <>
std::string describe<bool>(bool value) {
if (value) {
return "flag=yes";
}
return "flag=no";
}
int main() {
int score = ;
bool active = ;
std::cout << describe(score) << std::endl;
std::cout << describe(active) << std::endl;
return 0;
}
#include <iostream>
#include <string>
template <typename T>
std::string describe(T value) {
return "value=" + std::to_string(value);
}
template <>
std::string describe<bool>(bool value) {
if (value) {
return "flag=yes";
}
return "flag=no";
}
int main() {
int score = ;
bool active = ;
std::cout << describe(score) << std::endl;
std::cout << describe(active) << std::endl;
return 0;
}
#include <iostream>
#include <string>
template <typename T>
std::string describe(T value) {
return "value=" + std::to_string(value);
}
template <>
std::string describe<bool>(bool value) {
if (value) {
return "flag=yes";
}
return "flag=no";
}
int main() {
int score = ;
bool active = ;
std::cout << describe(score) << std::endl;
std::cout << describe(active) << std::endl;
return 0;
}
#include <iostream>
#include <string>
template <typename T>
std::string describe(T value) {
return "value=" + std::to_string(value);
}
template <>
std::string describe<bool>(bool value) {
if (value) {
return "flag=yes";
}
return "flag=no";
}
int main() {
int score = ;
bool active = ;
std::cout << describe(score) << std::endl;
std::cout << describe(active) << std::endl;
return 0;
}
#include <iostream>
#include <string>
template <typename T>
std::string describe(T value) {
return "value=" + std::to_string(value);
}
template <>
std::string describe<bool>(bool value) {
if (value) {
return "flag=yes";
}
return "flag=no";
}
int main() {
int score = ;
bool active = ;
std::cout << describe(score) << std::endl;
std::cout << describe(active) << std::endl;
return 0;
}
specialization
A specialized template version is selected for a specific type, such as `bool`, while the primary template handles the rest.