mercredi 26 juillet 2017

Overloading assignment operator in order to return std::vector

The function below converts the contents which is stored in the class cVector, to a std::vector and returns this.

template <class T> std::vector<T> cVector<T>::convertToStdVector()
{
    std::vector<T> vec;
    vec.resize(m_nSize);
    for (unsigned i=0; i<m_nSize; ++i) {
        vec[i] = m_pData[i];
    }
    return vec;
}

The above works perfect, now instead of using a function like this, I would like to overload the assignment operator and basically do the same thing.

I've tried the following:

template <class T> class cVector
{
public:

    cVector(unsigned nSize, AllocEnum eAllocType=MALLOC);
    cVector(T *pData, unsigned nSize, bool bCopy=false);

    // convert to std vector
    std::vector<T> operator=(const cVector<T> &cvec);

    //..
    //....
}

template <class T> std::vector<T> cVector<T>::operator=(const cVector<T> &cvec)
{
    std::vector<T> vec;
    vec.resize(m_nSize);
    for (unsigned i=0; i<m_nSize; ++i) {
        vec[i] = m_pData[i];
    }
    return vec;
}

This compiles fine, however when I try to call it in my code, e.g.

std::vector<float> vec = cVectorInstance;

Than I get the following error during compilation:

error: conversion from 'cVector' to non-scalar type 'std::vector >' requested"

I'm not sure what is going wrong here, I hope somebody can help / explain.

Aucun commentaire:

Enregistrer un commentaire