简体   繁体   中英

How to write the thinnest possible type wrapper

I have the following code:

#include <string>

template<typename T>
struct Wrapper {
    const T& in;
    Wrapper(const T& _in) : in(_in) {}

    operator const T&() const { return in; }
};

int main() {
    Wrapper<std::string> value("OMGOMGOMG");
    if(value == std::string("ads"))
        return 1;
}

And I get an error that there is no match for operator== with gcc/msvc - how can I get this code to work?

With type int it works but with std::string it doesn't.

EDIT:

I ended up writing them on my own - as separate templates with 2 arguments:

template<typename T> bool operator==(const WithContext<T>& lhs, const T& rhs){ return lhs.in == rhs; }
template<typename T> bool operator==(const T& lhs, const WithContext<T>& rhs){ return lhs == rhs.in; }
template<typename T> bool operator!=(const WithContext<T>& lhs, const T& rhs){ return lhs.in != rhs; }
template<typename T> bool operator!=(const T& lhs, const WithContext<T>& rhs){ return lhs != rhs.in; }
template<typename T> bool operator< (const WithContext<T>& lhs, const T& rhs){ return lhs.in <  rhs; }
template<typename T> bool operator< (const T& lhs, const WithContext<T>& rhs){ return lhs <  rhs.in; }
template<typename T> bool operator> (const WithContext<T>& lhs, const T& rhs){ return lhs.in >  rhs; }
template<typename T> bool operator> (const T& lhs, const WithContext<T>& rhs){ return lhs >  rhs.in; }
template<typename T> bool operator<=(const WithContext<T>& lhs, const T& rhs){ return lhs.in <= rhs; }
template<typename T> bool operator<=(const T& lhs, const WithContext<T>& rhs){ return lhs <= rhs.in; }
template<typename T> bool operator>=(const WithContext<T>& lhs, const T& rhs){ return lhs.in >= rhs; }
template<typename T> bool operator>=(const T& lhs, const WithContext<T>& rhs){ return lhs >= rhs.in; }

If you desire the Wrapper to have an equality comparison to the underlying type, give it one.

template<typename T>
struct Wrapper {
    const T& in;
    Wrapper(const T& _in) : in(_in) {}

    operator const T&() const { return in; }

    // compare to the underlying type
    bool operator==(T const& cmp) const { return cmp == in; }
    // compare the this type
    bool operator==(Wrapper const& cmp) const { return cmp.in == in; }
};

int main() {
    Wrapper<std::string> value("OMGOMGOMG");
    if(value == std::string("ads"))
        return 1;
}

The sample code presented here is for illustration, to support the premis that the desired comparison functions should be implemented. In reality, the comparison functions would probably land up being non member functions to support a more natural syntax.

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