Search⌘ K
AI Features

- Examples

Explore practical examples demonstrating high-performance C++ techniques such as template specialization, parameter packs, and perfect forwarding. Understand how these features enable compile-time computations, flexible object construction, and efficient code suited for embedded or safety-critical systems.

We'll cover the following...

Example 1

C++
// templateVariadicTemplates.cpp
#include <iostream>
template <typename... Args>
int printSize(Args... args){
return sizeof ...(args);
}
template<int ...>
struct Mult;
template<>
struct Mult<>{
static const int value= 1;
};
template<int i, int ... tail>
struct Mult<i, tail ...>{
static const int value= i * Mult<tail ...>::value;
};
int main(){
std::cout << std::endl;
std::cout << "printSize(): " << printSize() << std::endl;
std::cout << "printSize(template,2011,true): " << printSize("template",2011,true) << std::endl;
std::cout << "printSize(1, 2.5, 4, 5, 10): " << printSize(1, 2.5, 4, 5, 10) << std::endl;
std::cout << std::endl;
std::cout << "Mult<10>::value: " << Mult<10>::value << std::endl;
std::cout << "Mult<10,10,10>::value: " << Mult<10,10,10>::value << std::endl;
std::cout << "Mult<1,2,3,4,5>::value: " << Mult<1,2,3,4,5>::value << std::endl;
std::cout << std::endl;
}

Explanation

  • In the above example, we used a printSize function, which prints the number of elements (of any type) passed as arguments. It detects the number of elements on compile-time using the sizeof operator. In the case of an empty argument list, the function returns 0. ...