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


I would just do:



std::vector<std::string> v2(v1.begin(), v1.end());

      

+7


source


Just follow the simple



std::vector<std::string> v2;
v2.reserve(v1.size()); // Not really needed
for(auto x : v1) v2.emplace_back(x);

      

+1


source


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







All Articles