Автоматизация между контейнери на различни обекти с присвояване на копие

Имам разреден вектор от тип std::vector<SparseElement<T,I>>, където SparseElement е:

template<typename T, typename I = unsigned int>
struct SparseElement
{
    I index;
    T value;
    //............
    SparseElement &operator=(const std::pair<I,T> &pair);
 }

Тъй като използвам за попълване на разредения вектор a std::map<I,T>, който има като елементи std::pair<I,T>, искам решение за това, без да променям членовете 'index' и 'value' на SparseElement:

std::pair<I,T> a;
SparseElement<T,I> b;
b = a; // This is OK!
a = b; // Is there a solution on this problem?
// on containers:
std::vector<SparseElement<T,I>> vec;
std::map<I,T> m(vec.begin(), vec.end()); // Not working.
vec.assign(m.begin(), m.end()); // Working.

person Chameleon    schedule 21.03.2013    source източник
comment
a = b; може би template<class I, class T> std::pair<I,T>& operator=(pair<I,T> lhs, SparseElement<T, I> const & SE); като безплатна функция.   -  person RedX    schedule 21.03.2013
comment
@RedX - не, и аз си паднах по това. operator= трябва да бъде нестатична функция член, дефинирана от стандарта.   -  person Kiril Kirov    schedule 21.03.2013
comment
@KirilKirov Проклятие, щеше да е хубаво, ако беше възможно.   -  person RedX    schedule 21.03.2013
comment
След това може би добавете член operator std::pair<I,T>() преобразуващ член към вашия клас SparseElement.   -  person RedX    schedule 21.03.2013
comment
@RedX - хубаво, това трябва да работи.   -  person Kiril Kirov    schedule 21.03.2013


Отговори (1)


Пренаписване на отговора, за да помогне на общността

template<typename T, typename I = unsigned int>
struct SparseElement
{
    //..........
    I index;                //!< Index of element in vector
    T value;                //!< Value of element
    //..........
    //! Template copy constructor from a different type of \p std::pair
    //! This is useful for conversion from MapVector to SparseVector
    template<typename T2, typename I2>
    SparseElement(const std::pair<I2,T2> &s) : index(s.first), value(s.second) {}
    //..........
    //! Template copy assign from a different type of \p std::pair
    //! This is useful for conversion from MapVector to SparseVector
    template<typename T2, typename I2>
    SparseElement &operator=(const std::pair<I2,T2> &s) { index = s.first; value = s.second; return *this; }

    //! Implicit conversion from SparseElement to a \p std::pair
    //! This is useful for conversion from SparseVector to MapVector
    operator std::pair<const I,T>() { return std::pair<const I,T>(index, value); }
};
person Chameleon    schedule 21.03.2013