Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass template function to transform without lambda

I currently have the c++11 function:

template<class IteratorIn>
std::string to_string_join(IteratorIn first, IteratorIn last, std::string joiner) {

    std::vector<std::string> ss(last - first);

    std::transform(
        first, last, begin(ss),
        [](typename std::iterator_traits<IteratorIn>::value_type d) {
            return std::to_string(d);
        }
    );

    return boost::algorithm::join(ss, joiner);
}

Which can be used like:

std::vector<int> is{-1, 2, 62, 4, -86, 23, 8, -0,2};

std::cout << to_string_join(begin(is), end(is), ", ") << std::endl;

To output :

"-1, 2, 62, 4, -86, 23, 8, 0 ,2".

I read in another SO post "convert-vectordouble-to-vectorstring-elegant-way" that the lambda is not required. However I haven't been able to achieve removing the lambda.

I suspect it should look similar to this:

std::transform(
    first, last, begin(ss),
    std::to_string<typename std::iterator_traits<IteratorIn>::value_type>
);

That results in the compilation error:

"error: expected ‘(’ before ‘>’ token".

How can I go about passing to_string without the lambda?

like image 747
JulianAustralia Avatar asked Jan 09 '23 06:01

JulianAustralia


1 Answers

The error occurs because std::to_string is not a function template. You're looking for a static_cast, not a template argument.

std::transform(
    first, last, begin(ss),
    static_cast<std::string(*)(typename std::iterator_traits<IteratorIn>::value_type)>(std::to_string)
);
like image 179
Praetorian Avatar answered Jan 16 '23 17:01

Praetorian