Skip template function for conversion without lambda

I currently have a 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);
}

What can be used as:

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 the message convert-vectordouble-to-vectorstring-elegant-way that lambda is not required. However, I could not get the lambda removed.

I suspect it should look something like this:

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

This results in a compilation error:

"error: expected '(before'> token".

How do I go to_string without lambda?

+4
source share
1 answer

The error occurs because it is std::to_stringnot a function template. You are looking for 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)
);
+9

All Articles