2

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 ?

3
  • 2
    Replace the cast with &addValue<int, 5>, it should work on any modern compiler...
    – K-ballo
    Dec 30, 2012 at 21:20
  • 1
    You've reserved no space for your dest. consider a back_inserter or resize it to the size of source. (or I'm really missing the obvious, which happens a lot)
    – WhozCraig
    Dec 30, 2012 at 21:20
  • Stop using C-style casts: with one extremely narrow exception you can do a C++ style cast and get the same result, while preventing dangerous undefined behavior from silently occurring, or making it obvious that you are doing something dangerous. Dec 30, 2012 at 21:23

2 Answers 2

3

The cast is not your problem, you are outputting elements to an empty vector. Instead you could resize the space you will need:

dest.resize(source.size());

or better yet let transform figure that out:

std::transform(
    source.begin(), source.end()
  , std::back_inserter( dest ) // needs <iterator>
  , &addValue<int, 5> // cast should not be needed
);

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 call reserve to avoid internal reallocation:

dest.reserve(source.size());
// dest is still empty

std::transform(
    source.begin(), source.end()
  , std::back_inserter( dest ) // needs <iterator>
  , &addValue<int, 5> // cast should not be needed
);
1
  • +1 thats kinda of what I thought was the issue (and I don't think the amp (&) is needed either, but I have some pretty bad practices and this may be one of them).
    – WhozCraig
    Dec 30, 2012 at 21:24
2

The problem of the segmentation fault is that dest is empty but you are assigning values to it! There are two approaches to make sure that there are elements you can actually assign to:

  1. You can set the size of dest before std::transform()ing the data: dest.resize(source.size()).
  2. You can instruct the algorithm to insert objects at the end of dest using a std::back_insert_iterator<...>: std::transform(source.begin(), source.end(), std::back_inserter(dest), function) (where function is a suitable approach to get hold of a function object).

Personally, I wouldn't use a pointer to a function anyway because it is quite likely that compiler won't inline the function call though a pointer to a function anyway. Instead, I'd use a suitable function object:

template <int N>
struct addValue {
    template <typename T>
    T operator()(T value) const { return value + N; }
};

... and then just use

std::transform(source.begin(), source.end(), std::back_inserter(dest), addValue<5>());
2
  • +1. for a general solution should the param be const T& or perhaps an SFINAE overload specialized against is_class (just learning about SFINAE and always looking for places where it potentially applies, so please take my question as genuine curiosity, thanks)
    – WhozCraig
    Dec 30, 2012 at 21:32
  • @WhozCraig: The proper solution would probably be the use of T&& instead of T. Although choosing a function overload based on whether T is simple type or not would work I'd think it wouldn't be worth it. Dec 30, 2012 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.