简体   繁体   中英

Providing const and non-const version of functions

Maybe it is a trivial question, but I can't actually find an answer. If I have a class like in the example below do I need to provide both const and non-const version of functions like in case of std::vector? Would a single constexpr function do the same job?

template <typename Type>
class Collection
{
    public:

        virtual ~Collection() {}

        virtual size_t size() noexcept = 0;
        virtual size_t size() const noexcept = 0;
        virtual Type operator[](size_t index) noexcept = 0;
        virtual Type operator[](size_t index) const noexcept = 0;
};

It depends. If the non-const version would do the same thing as the const version, then no. If someone has a non-const instance of a class, they can still call const methods.

There are some methods that may need both. Consider your indexing operator. If it instead returned a reference to the type, you would probably want both:

virtual Type& operator[](size_t index) noexcept = 0;
virtual const Type& operator[](size_t index) const noexcept = 0;

The methods aren't exactly the same because they are returning different types. This would mean that if someone has a const instance of your type, they could not get a mutable reference to an element.

A single constexpr function could do the job as long as the potential const/non-const implementations would be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM