Search⌘ K

- Examples

Explore how to create and use function templates in C++ for various data types, including built-in and user-defined types. Learn about type deduction, specifying return types, and customizing comparisons using function objects and lambdas. This lesson provides practical examples to understand template flexibility and type-safe programming in high-performance embedded systems.

Example 1

C++
// templateArgumentDeduction.cpp
#include <iostream>
template <typename T>
bool isSmaller(T fir, T sec){
return fir < sec;
}
template <typename T, typename U>
bool isSmaller2(T fir, U sec){
return fir < sec;
}
template <typename R, typename T, typename U>
R add(T fir, U sec){
return fir + sec;
}
int main(){
std::cout << std::boolalpha << std::endl;
std::cout << "isSmaller(1,2): " << isSmaller(1,2) << std::endl;
// std::cout << "isSmaller(1,5LL): " << isSmaller(1,5LL) << std::endl; // ERROR
std::cout << "isSmaller<int>(1,5LL): " << isSmaller<int>(1,5LL) << std::endl;
std::cout << "isSmaller<double>(1,5LL): " << isSmaller<double>(1,5LL) << std::endl;
std::cout << std::endl;
std::cout << "isSmaller2(1,5LL): " << isSmaller2(1,5LL) << std::endl;
std::cout << std::endl;
std::cout << "add<long long int>(1000000,1000000): " << add<long long int>(1000000, 1000000) << std::endl;
std::cout << "add<double,double>(1000000,1000000): " << add<double,double>(1000000, 1000000) << std::endl;
std::cout << "add<double,double,float>(1000000,1000000): " << add<double,double,float>(1000000, 1000000) << std::endl;
std::cout << std::endl;
}

Explanation

In the above example, we defined 3 function templates.

  • isSmaller takes two arguments, which must have the same type. The template returns true if the first element is less than the second element (line 6). Invoking the function with arguments of a different type would give a compile-time error (line 25).

  • isSmaller2 takes two arguments, which can have different types. The template returns true if ...