封装简单算术类型的c++

c++ wrapping simple arithmetic types

本文关键字:c++ 类型 简单 封装      更新时间:2023-10-16

我想用默认构造函数扩展int32_t和int64_t。我想我必须使用来自boost operators .hpp的operator<>和operator2<>来定义新的类型。

  1. 这就够了吗,有例子吗?
  2. 这种方法对c++11/14有影响吗?我没有看到在operators.hpp中使用通用引用。简单地输入这些类来利用c++11/14的特性有意义吗?虽然冗长但相对简单。

我理解这样做的动机,但是不让整型未初始化的做法最终可能会减少心痛。

然而,这可能是一个很好的起点。您会注意到,普通算术运算不需要操作符。

#include <iostream>

template<class Type, Type original_value>
struct safe_integral
{
    safe_integral()
    : _v(original_value)
    {}
    safe_integral(Type t)
    : _v(t)
    {}

    operator const Type&() const { return _v; }
    operator Type&() { return _v; }
private:
    Type _v;
};
using namespace std;
auto main() -> int
{
    using safe_int = safe_integral<int, 0>;
    safe_int x;
    cout << "original value: " << x << endl;
    x += 6;
    cout << "adding 6: " << x << endl;
    safe_int y = x;
    safe_int z = x + 6;
    safe_int w = x + z;
    cout << "w is : " << w << endl;

    return 0;
}
预期输出:

original value: 0
adding 6: 6
w is : 18