Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to Only Pass Second Template Parameter

So I have a template function which has a defaulted 2nd argument. It's 1st argument can be deduced, so something like:

template <typename F, typename S = int>
void foo(const F param)

This works fine in the general case, I'll just call foo(bar). But in the case where I want to specify the second argument, I cannot do this: foo<char>(bar), because char is taken as F. Obviously this isn't the case because bar isn't a char, so F should be deducible.

Is there a way that I can pass only one template argument here which will apply to S, still have F be deduced, and still default S in the general case?

like image 749
Jonathan Mee Avatar asked Feb 14 '19 15:02

Jonathan Mee


People also ask

How will you restrict the template for a specific datatype?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

Can template have default parameters?

You cannot give default arguments to the same template parameters in different declarations in the same scope. The compiler will not allow the following example: template<class T = char> class X; template<class T = char> class X { };

Can a template be a template parameter?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)

How long template parameters will be valid?

3. What is the validity of template parameters? Explanation: Template parameters are valid inside a block only i.e. they have block scope.


Video Answer


1 Answers

Just reorder template arguments:

template <typename S = int, typename F>
void foo(const F param);

template can have default at any place. At the end, all template parameters should be provided, defaulted or deduced.

like image 118
Jarod42 Avatar answered Oct 19 '22 07:10

Jarod42