如何编写尽可能薄的类型包装器
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;
}
我收到一个错误,表明 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;
}
这里提供的示例代码用于说明,以支持应实现所需比较函数的前提。实际上,比较函数可能会成为非成员函数,以支持更自然的语法。
相关文章:
- 如何在c++迭代器类型中包装std::chrono
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 包装C++类时不完整的类型 GLFWwindow
- 如何包装一个函数以适应另一个函数的所需类型
- 通过包装器从 C 访问C++ API 时,如何访问枚举类型
- 为 Sql 服务器实现 odbc 包装器.将数据库数据读取为字符或要求驱动程序将数据转换为 C 类型
- 有什么方法可以包装自动类型扣除的助推"tee"流的构造?
- 有没有办法将输入类型包装到C++中的模板类?
- 包装任意类型/非类型模板类的模板类
- 在 stl 容器包装器中定义迭代器类型
- 如何在 C++ 中正确包装类型
- 如何包装对象,使它们成为无法交互的单独类型?
- 包装一个函数,在 Cython 中返回复杂类型的向量
- 如何编写尽可能薄的类型包装器
- C++类型包装器 printf 打印错误的浮点值
- 防止在std::函数中使用不同类型包装lambda
- 将每个类型包装在模板化类中的可变模板中
- 如何在c++中优化一个简单的数字类型包装器类
- 如何用未知类型包装变差函数
- c++基本类型包装器