Complicated copying with std::transform
You might have noticed, way back when we presented the implementation of std::copy
, that the value_type
of the two iterator type parameters were not constrained to be the same. This is a feature, not a bug! It means that we can write code that relies on implicit conversions and it will just Do The Right Thing:
std::vector<const char *> input = {"hello", "world"}; std::vector<std::string> output(2); std::copy(input.begin(), input.end(), output.begin()); assert(output[0] == "hello"); assert(output[1] == "world");
Looks trivial, right? Look closely! Deep within our instantiation of std::copy
is a call to the implicit constructor that converts const char *
(the type of *input.begin()
) to std::string
(the type of *output.begin()
). So for the umpteenth time, we're seeing an example of generic code that does surprisingly complicated operations simply by virtue of being given certain iterator types.
But sometimes you want to...