Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ function template specify second template parameter type

Tags:

c++

templates

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?

like image 941
tesla1060 Avatar asked Apr 05 '18 08:04

tesla1060


People also ask

Can there be more than one arguments to templates?

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.

Can we pass Nontype parameters 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.

Is used in a function template to specify a generic data type?

C++ Function Template Syntax The class keyword is used to specify a generic type in a template declaration.

What is the difference between typename and class in template?

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.


1 Answers

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);
like image 85
Oliv Avatar answered Sep 28 '22 21:09

Oliv