简体   繁体   中英

Non-type function template parameters

I am reading C++ Templates Complete Guide and came across this non-type function template parameters code (I have added the main() and other parts except the function definition and call):

#include <vector>
#include <algorithm>
#include <iostream>

template <typename T, int value>
T add (T const & element){
  return element + value;
}

int main() {
  int a[] = {1,2,3,4};
  int length = sizeof (a) / sizeof (*a);
  int b[length];
  std::transform (a, a + length, b, (int(*)(int const &))add <int, 5>); //why?
  std::for_each (b, b + length, [](int const & value){ std::cout << value << '\n'; });
  return 0; 
}

I did not understand after reading from the book why we need typecasting of the function call?

EDIT: Explaination from the book:

add is a function template, and function templates are considered to name a set of overloaded functions (even if the set has only one member). However, according to the current standard, sets of overloaded functions cannot be used for template parameter deduction. Thus, you have to cast to the exact type of the function template argument:...

Compiler: g++ 4.5.1 on Ubuntu 10.10

Strictly speaking, you couldn't refer to the specialization of a function template by simply giving a template argument list. You always had to have a target type around (like, a function parameter type you pass to, or a cast type you cast to, or a variable type you assign to).

That was the case even if the target type is completely free of template parameters, for example

template<typename T> void f() { }
template<typename T> void g(T) { }

int main() {
  g(f<int>); // not strictly valid in C++03
  g((void(*)())f<int>); // valid in C++03
}

The committee added rules that were adopted into C++0x and by popular compilers in their C++03 mode that made it possible to omit a target type if you supply a complete template argument list supplying types for all template parameters, together with all default template arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM