Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65945888/c-cast-template-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...