如何编写尽可能薄的类型包装器

How to write the thinnest possible type wrapper

本文关键字:类型 包装 何编写 尽可能      更新时间:2023-10-16

我有以下代码:

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

我收到一个错误,表明 gcc/msvc 的operator==不匹配 - 如何让这段代码工作?

对于类型 int,它可以工作,但对于std::string

它不起作用。

编辑:

我最终自己编写了它们 - 作为带有 2 个参数的单独模板:

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

如果您希望Wrapper与基础类型进行相等比较,请给它一个。

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

这里提供的示例代码用于说明,以支持应实现所需比较函数的前提。实际上,比较函数可能会成为非成员函数,以支持更自然的语法。