I’m reading the C++ Templates: The complete guide book and in chapter 4 (4.2 Nontype Function Template Parameters) is an example of a template function that can be used with STL containers to add a value to each element of a collection. Here is the complete program:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
template<typename T, int VAL>
T addValue(T const& x)
{
return x + VAL;
}
int main()
{
std::vector<int> source;
std::vector<int> dest;
source.push_back(1);
source.push_back(2);
source.push_back(3);
source.push_back(4);
source.push_back(5);
std::transform(source.begin(), source.end(), dest.begin(), (int(*)(int const&)) addValue<int, 5>);
std::copy(dest.begin(), dest.end(), std::ostream_iterator<int>(std::cout, ", "));
return 0;
}
I had to make that ugly cast because the book states that:
Note that there is a problem with this example: addValue<int,5> 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:
std::transform (source.begin(), source.end(), // start and end of source
dest.begin(), // start of destination
(int(*)(int const&)) addValue<int,5>); // operation
My problem is that I get an segmentation fault when running the program. I am building it using Clang on the Mac.
Is the cast incorrect or what else could the problem be ?
The cast is not your problem, you are outputting elements to an empty
vector. Instead you couldresizethe space you will need:or better yet let
transformfigure that out:although if you do know how much space it will take,
resize-ing the vector will have better performance as it will avoid internal reallocation as items are added. Another alternative is to callreserveto avoid internal reallocation: