gpt4 book ai didi

c++ - 如何编写最薄的类型包装器

转载 作者:太空狗 更新时间:2023-10-29 20:53:44 24 4
gpt4 key购买 nike

我有以下代码:

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

我收到一个错误,指出 operator== 与 gcc/msvc 不匹配 - 我怎样才能让这段代码工作?

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

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

关于c++ - 如何编写最薄的类型包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com