Domanda

Consider a templated class that I've created called myList, it basically extends the std::list object provided in the C++ STL. I've overridden a few functions such as size(), front() and back() but have not touched the sort() function that is provided with std::list.

Basically, I want to be able to sort myList, consider my decorator implementation:

#import "myList.h"

template <typename T>
class myListDecorator : public myList<T> {

public:
    myListDecorator() : m_list(myList<T>()){}

    myListDecorator(const myList<T> &my_list) {
        m_list = my_list.sort();
    }

private:
    myList<T> m_list;

};

Whenever I create a myList (in these case using objects of type double) I get the following error:

Candidate function not viable: no known conversion from 'const myList<double>' to 'std::list<double, std::allocator<double>>' for object argument.

Do I have to override the sort() function in myList and implement my own sort for this to work?

EDIT:

A few of the comments pointed out how confusing it was having effectively two myList objects in this class. I've updated my code to be more 'correct'/'best practice'. It now does what I intended it to do and is much tidier:

#include "myList.h"

template <typename T>
class myListDecorator : public myList<T> {

public:
    myListDecorator() : myList<T>(myList<T>()){}

    myListDecorator(const myList<T> &my_list) : myList<T>(my_list){
        this->sort();
    }
};
È stato utile?

Soluzione

Your my_list is const. The sort() member function modifies the list in place, and cannot do that with a constant list. (Note that the return type of sort() is void.)

You should be able to:

myListDecorator(const myList<T> &my_list): m_list(my_list) {
    m_list.sort();
}

Altri suggerimenti

The reason is that your are trying to cast a const myList to a non-const type. BTW, '#import' is not a standard C/C++ preprocessor statement.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top