lundi 17 juin 2019

Why does the following `std::transform` example need a function pointer instead of a function object?

The function template std::transform() takes a range, operates on it component-wise with an operator, and saves the result in another range. In the following example, the function takes a generic std::initializer_list called nl and operates on it with (std::string (*)(T)) std::to_string to transform all of its entries into strings and then stores the result in an array of strings called buffer.

class num_list
{
public:
    template<typename T>
    num_list(std::initializer_list<T> nl):
        size{nl.size()},
        buffer(new std::string[size])
    {
        std::transform(nl.begin(), nl.end(), // input sequence
        buffer,                              // output result
        (std::string (*)(T))std::to_string); // unary operator
    }
    //...
private:
    std::size_t size;
    std::string * buffer;
};

I am wondering why we need to typecast std::to_string into a function pointer for this to work. Why does the code fail to compile with C++11 if we drop the casting to pointer-to-function type (std::string (*)(T))? I can't decipher the complain thrown by the compiler.

error: no instance of overloaded function "std::transform" matches the argument list

Aucun commentaire:

Enregistrer un commentaire