Use constructor as predicate
Can a constructor be used as a predicate? So far I can do this:
std::vector<const char*> v1 = {
"Hello", "from", "GCC", __VERSION__, "!"
};
std::vector<std::string> v2(v1.size());
std::transform(v1.begin(), v1.end(), v2.begin(),
[] (const char* s) { return std::string(s); });
But I want to do something std::tranform( ..., std::string)
. I've tried std::string::string
, std::string::basic_string
and std::string::basic_string<char>
.
+3
source to share
3 answers
The trick is that we need to pass typename
in template
, and then we can use that to call the constructor you want.
This is what I came up with:
template<typename source, typename destination, typename iter, typename iter2>
void transform_object(iter begin, iter end, iter2 begin2)
{
std::transform(begin, end, begin2, [](source s){ return destination(s); } );
}
And use it with source code:
transform_object<const char*, std::string>(v1.begin(), v1.end(), v2.begin());
0
source to share