matanmarkind
matanmarkind

Reputation: 247

Call template function with non-type parameters explicit and type parameters implicit

I want to create a template function that has both type template parameters, which can be deduced from the parameters passed to the function, and non-type template parameters, that will be placed explicitly. It seems like the compiler can deduce what each type is, but if I specify the non-type template parameter it wants all the template parameters. Can I specify just the non-type template parameters, or is it an all or nothing deal?

#include <iostream>
#include <typeinfo>

template <typename T, bool bPrint=true>
void f(T var) {
  if (bPrint)
    std::cout <<  typeid(var).name() << std::endl;
}

int main() {
  f(3); //works
  f<false>(3); //error: template argument deduction/substitution failed
}

Upvotes: 1

Views: 148

Answers (1)

krzaq
krzaq

Reputation: 16421

You can, but deduced template parameters need to be at the end of the argument list. You can make your code compile by reordering parameters of your function template:

template < bool bPrint=true, typename T>
void f(T var) {
  if (bPrint)
    std::cout <<  typeid(var).name() << std::endl;
}

demo

Upvotes: 3

Related Questions