![](/img/trans.png)
[英]Is there such a thing as the thinnest wrapper around a class to add methods?
[英]How to write the thinnest possible type wrapper
我有以下代码:
#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;
}
此处提供的示例代码仅用于说明,以支持应实现所需比较功能的前提。 实际上,比较函数可能会成为非成员函数以支持更自然的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.