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?
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.
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 { };
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.)
3. What is the validity of template parameters? Explanation: Template parameters are valid inside a block only i.e. they have block scope.
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.
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