Non-Type Template Parameters

I am reading a complete guide to C ++ templates and came across this code of non-type template parameters (I added the main () and other parts besides 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; } 

After reading from the book, I did not understand why we need to attribute a function call?

EDIT: Explanation from the book:

add is a function template, and it is believed that function templates are called a set of overloaded functions (even if the set has only one element). However, according to the current standard, sets of overloaded functions cannot be used to subtract a template parameter. Thus, you need to specify the exact value of the function template argument: ...

Compiler: g ++ 4.5.1 on Ubuntu 10.10

+6
source share
1 answer

Strictly speaking, you could not refer to the specialization of a function template by simply specifying a list of template arguments. You should always have the type of target (for example, the type of the parameter of the function you are going to, or the type of the throw you are pointing to, or the type of the variable you are assigning).

This was true 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 the rules that were adopted in C ++ 0x and by popular compilers in their C ++ 03 mode, which made it possible to omit the target type if you provide a complete list of template arguments, providing types for all template parameters, along with all template arguments default.

+6
source

Source: https://habr.com/ru/post/893456/


All Articles