Dmitry
Dmitry

Reputation: 2158

C++ cast template type

Consider the following code snippet :

[[nodiscard]] bool operator==(const BasicIterator<const Type>& rhs) const noexcept {
    if( this == &rhs ) {
        return true;
    }
    return node_ == rhs.node_;
}

[[nodiscard]] bool operator==(const BasicIterator<Type>& rhs) const noexcept {
    // how to call existing operator== implementation ??
    //return operator==( rhs );
}

How should I use the same implementation for both operator==? Is it possible to call operator== <const Type> version from operator== <Type>?

Is there any cast for template types in this case?

Upvotes: 2

Views: 106

Answers (1)

warchantua
warchantua

Reputation: 1213

Is Type a template? If not, maybe make it a template?

template <typename T>
[[nodiscard]] bool operator==(const BasicIterator<T>& rhs) const noexcept {
    if( this == &rhs ) {
        return true;
    }
    return node_ == rhs.node_;
}

If you do not want to expose this template to users, hide it somewhere and use in implementation:


private: 
template <typename T>
[[nodiscard]] bool operator==(const BasicIterator<T>& lhs, const BasicIterator<T>& rhs) const noexcept {
    if( &lhs== &rhs ) {
        return true;
    }
    return lhs.node_ == rhs.node_;
}

public:
[[nodiscard]] bool operator==(const BasicIterator<const Type>& rhs) const noexcept {
    return operator==<const Type>(*this, rhs);
}

[[nodiscard]] bool operator==(const BasicIterator<Type>& rhs) const noexcept {
    return operator==<Type>(*this, rhs);
}

Upvotes: 1

Related Questions