just started learning template programming, I have the following code,
template<typename T, typename U>
void add(T x, U y)
{
cout<< x + y <<endl;
}
I can call this by,
add(1, 2);
add<int, int>(1, 2);
add<int>(1, 2.0);
In the third case, I believe that means I specified [T=int]
, and compiler will deduce [U=double]
My question is how can I specify the second parameter type explicitly?
Can there be more than one argument to templates? Yes, like normal parameters, we can pass more than one data type as arguments to templates.
Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.
C++ Function Template Syntax The class keyword is used to specify a generic type in a template declaration.
There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers. I myself prefer <typename T> as it more clearly describes its use; i.e. defining a template with a specific type.
What about add(1,(int)2.0);
.
In theory according to template argument deduction rules, this causes the second template parameter to be deduced as int
.So this is stricktly equivalent to this hypothetical syntax add<U=int>(1,2.0);
So this is the way to specify the second template argument!
It is impossible to find an equivalent syntax if the second template argument is non-deductible:
template<class T>
struct t_{
using type = T;
};
template<class T,class U>
auto add(T, typename t_<U>::type);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With