Search⌘ K
AI Features

Examples - Template Code Simplifications

Discover how C++17 enhances template programming through code simplifications like if constexpr for type-based decisions, recursive pointer handling, and custom get<N> functions enabling structured bindings for private members. Learn practical examples that improve readability and versatility in your template code.

We'll cover the following...

Line Printer

You might have already seen the below example in the Jump Start section at the beginning of this part of the course. Here, we’ll dive into the details.

C++ 17
#include <iostream>
using namespace std;
template<typename T> void linePrinter(const T& x)
{
if constexpr (std::is_integral_v<T>){
std::cout << "num: " << x << '\n';
}
else if constexpr (std::is_floating_point_v<T>){
const auto frac = x - static_cast<long>(x);
std::cout << "flt: " << x << ", frac " << frac << '\n';
}
else if constexpr(std::is_pointer_v<T>){
std::cout << "ptr, ";
linePrinter(*x);
}
else{
std::cout << x << '\n';
}
}
template<typename ... Args>
void PrintWithInfo(Args ... args)
{
(linePrinter(std::forward<Args>(args)), ...); // fold expression over the comma operator
}
int main(){
std::cout << "-- extra info: \n";
int i = 10;
PrintWithInfo(&i, std::string("hello"), 10, 20.5, 30);
}

linePrinter uses if constexpr to check the input type. Based on that, we can output additional messages. An interesting thing happens with the pointer type - when a pointer is detected the ...