vendredi 28 juillet 2017

Why does the compiler search for type,allocator instead of type&?

I'm trying to write a basic function to write a vector of array-like elements to a CSV file:

template <typename T>
void writeCSV(std::string filename, std::vector<T>& mat)
{
    std::ofstream outfile(filename);

    for (std::vector<T>::iterator it = mat.begin(); it != mat.end(); ++it)
    {
        outfile << *it << std::endl;
    }
}

which is used for types for which I have overloaded the << operator as:

std::ostream &operator<<(std::ostream &os, Point2D const &m) {
    return os << m.x << "," << m.y;
}

I use the function as:

std::vector<Point2D> points = complicated_function();
writeCSV<Point2D>("file.csv", points);

This compiles & works just fine in VS2015, but fails when I try to use the exact same code in Simulink (using vs15 as compiler), with the error:

error C2664: 'void csv::writeCSV<Point2d>
(std::string,std::vector,std::allocator>> &)': cannot convert argument 2 from 'std::vector' to 'std::vector,std::allocator>> &'
    with
    [
        _Ty=point_t
    ]

(For some reason, the developer in charge of complicated_function typedef'd all the base types, and point_t is an alias for Point2D.)

My first question is: what am I doing wrong? Additionally, why is the compiler trying to find an allocator?

Second question: when debugging, I tried to pass mat by copy instead of reference:

void writeCSV(std::string filename, std::vector<T> mat)

In this case, the code does not compile at all in VS, with the following error:

Error C2679 binary '<<': no operator found which takes a 
right-hand operand of type 'std::vector<T,std::allocator<_Ty>>' 
(or there is no acceptable conversion)  

However, when I explicitly take care of the overloading by defining by hand

void writeCSV(std::string filename, std::vector<Point2D> mat)

everything works fine, although from my (limited) understanding of templates, this should be almost equivalent since the compiler is supposed to generate one function for each T it encounters. What am I missing?

Thanks.

Aucun commentaire:

Enregistrer un commentaire