- Examples
Let's check out some examples of template arguments.
Example 1: Deduction of Template Arguments #
Press + to interact
// 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; // ERRORstd::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 example above, we have defined 3 function templates
isSmaller
takes two arguments which have the same type and returnstrue
if the first element is less than the second element (line 6). Invoking the function with arguments of