原始数据类型的包装类

发布于 2024-12-14 12:36:58 字数 1697 浏览 0 评论 0原文

在设计解决方案时,有时为原始数据类型提供包装类可能会很方便。考虑一个表示数值的类,可以是 doublefloatint

class Number {
private:
    double val;

public:
    Number(int n) : val(n) { }
    Number(float n) : val(n) { }
    Number(double n) : val(n) { }

    // Assume copy constructors and assignment operators exist

    Number& add(const Number& other) {
        val += other.val;
        return *this;
    }

    int to_int() const { return (int) val; }
    float to_float() const { return (float) val; }
    double to_double() const { return val; }
};

现在假设我有一个这样的函数:

void advanced_increment(Number& n) {
    n.add(1);
}

我会这样使用这个函数:

Number n(2);
advanced_increment(n); // n = 3

这听起来很简单。但如果函数是这样的呢?

void primitive_increment(int& n) {
    ++n;
}

请注意,增量是一个示例。假设该函数将对原始数据类型执行更复杂的操作,它们也应该能够在 Number 类型上执行而不会出现任何问题。

我将如何像以前一样使用该功能?如:

Number n(2);
primitive_increment(n);

如何使我的 Number 类与 primitive_increment 兼容?如何为原始数据类型创建一个包装类,使其在需要这些数据类型的任何地方都兼容?

到目前为止,我只找到了两个解决方案。一种是创建一个函数,例如 double& Number::get_value(),然后像 primitive_increment(n.get_value()); 一样使用它。第二种解决方案是创建隐式转换方法,例如 Number::operator int&();但这些可能会导致许多不明确的调用,并使代码变得混乱。

我想知道是否有任何其他解决方案来实现这些类型的包装器并保留其原始功能。

更新:

为了进一步澄清,在实际项目中,这里的目的是在设计此类解决方案时使所有数据类型都派生自一个基类,该基类通常称为Object 。一个限制是不应使用外部库。因此,如果我有一个具有指向 Object 类型的指针的容器,它应该能够保存任何任意值(无论是否是原始值),并执行 Object< 上允许的任何原始操作。 /代码>。我希望这能更好地解释它。

In designing a solution, sometimes it may be convenient to provide wrapper classes for primitive data types. Consider a class that represents a numeric value, be it a double, a float, or an int.

class Number {
private:
    double val;

public:
    Number(int n) : val(n) { }
    Number(float n) : val(n) { }
    Number(double n) : val(n) { }

    // Assume copy constructors and assignment operators exist

    Number& add(const Number& other) {
        val += other.val;
        return *this;
    }

    int to_int() const { return (int) val; }
    float to_float() const { return (float) val; }
    double to_double() const { return val; }
};

Now suppose that I have a function as such:

void advanced_increment(Number& n) {
    n.add(1);
}

And I would use this function as such:

Number n(2);
advanced_increment(n); // n = 3

This sounds easy enough. But what if the function was like this?

void primitive_increment(int& n) {
    ++n;
}

Note that the increment is an example. It is assumed that the function would perform more complicated operations on primitive data types that they should also be able to perform on Number types without any issues.

How would I use the function exactly as before? As in:

Number n(2);
primitive_increment(n);

How could I make my Number class compatible with primitive_increment? How could I create a wrapper class for primitive data types that would be compatible anywhere that these data types are required?

So far, I have only found two solution. One is to create a function such as double& Number::get_value() and then use it like primitive_increment(n.get_value());. The second solution is to create implicit conversion methods such as Number::operator int&(); but these can result in many ambiguous calls and would make the code confusing.

I'm wondering if there is any other solution to implement these types of wrappers and retain their primitive functionality.

Update:

To further clarify, in the actual project, the intent here is to make all data types derived from one base class that is commonly referred to as Object when designing such solution. A constraint is that no outside library should be used. Therefore, if I have a container that has pointers to the type Object, it should be able to hold any arbitrary value, primitive or not, and perform any primitive operation that is allowed on Object. I hope this explains it better.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

橘香 2024-12-21 12:36:58

C++11 具有显式运算符重载。

struct silly_wrapper {
  int foo;
  explicit operator int&() { return foo; }
};

void primitive_increment(int& x) { ++x; }


int main()
{
   silly_wrapper x;
   primitive_increment(x); // works
   x += 1; // doesn't work - can't implicitly cast
}

C++11 has explicit operator overloads.

struct silly_wrapper {
  int foo;
  explicit operator int&() { return foo; }
};

void primitive_increment(int& x) { ++x; }


int main()
{
   silly_wrapper x;
   primitive_increment(x); // works
   x += 1; // doesn't work - can't implicitly cast
}
走过海棠暮 2024-12-21 12:36:58
class Number {
    enum ValType {DoubleType, IntType} CurType;
    union {
        double DoubleVal;
        int IntVal;
    };
public:
    Number(int n) : IntVal(n), CurType(int) { }
    Number(float n) : DoubleVal(n), CurType(DoubleType) { }
    Number(double n) : DoubleVal(n), CurType(DoubleType) { }

   // Assume copy constructors and assignment operators exist

    Number& add(const Number& other) {
        switch(CurType) {
        case DoubleType: DoubleVal += other.to_double(); break;
        case IntType: IntVal+= other.to_int(); break;
        }
        return *this;
    }

    int& to_int() { 
        switch(CurType) {
        case DoubleType: IntVal = DoubleVal; CurType = IntType; break;
        //case IntType: DoubleVal = IntVal; CurType = DoubleType; break;
        }
        return IntVal; 
    }
    const int to_int() const { 
        switch(CurType) {
        case DoubleType: return (int)DoubleVal;
        case IntType: return (int)IntVal;
        }
    }
    const float to_float() const { 
        switch(CurType) {
        case DoubleType: return (float)DoubleVal;
        case IntType: return (float)IntVal;
        }
    }

    double& to_double() { 
        switch(CurType) {
        //case DoubleType: IntVal = DoubleVal; CurType = IntType; break;
        case IntType: DoubleVal = IntVal; CurType = DoubleType; break;
        }
        return DoubleVal; 
    }
    const double to_double() const { 
        switch(CurType) {
        case DoubleType: return (double)DoubleVal;
        case IntType: return (double)IntVal;
        }
    }
};

void primitive_increment(int& n) {
    ++n;
}

int main() {
    Number pi(3.1415);
    primitive_increment(pi.to_int());
    //pi now is 4
    return 0;
}

我承认这很尴尬,而且不是理想的情况,但它解决了给定的问题。

class Number {
    enum ValType {DoubleType, IntType} CurType;
    union {
        double DoubleVal;
        int IntVal;
    };
public:
    Number(int n) : IntVal(n), CurType(int) { }
    Number(float n) : DoubleVal(n), CurType(DoubleType) { }
    Number(double n) : DoubleVal(n), CurType(DoubleType) { }

   // Assume copy constructors and assignment operators exist

    Number& add(const Number& other) {
        switch(CurType) {
        case DoubleType: DoubleVal += other.to_double(); break;
        case IntType: IntVal+= other.to_int(); break;
        }
        return *this;
    }

    int& to_int() { 
        switch(CurType) {
        case DoubleType: IntVal = DoubleVal; CurType = IntType; break;
        //case IntType: DoubleVal = IntVal; CurType = DoubleType; break;
        }
        return IntVal; 
    }
    const int to_int() const { 
        switch(CurType) {
        case DoubleType: return (int)DoubleVal;
        case IntType: return (int)IntVal;
        }
    }
    const float to_float() const { 
        switch(CurType) {
        case DoubleType: return (float)DoubleVal;
        case IntType: return (float)IntVal;
        }
    }

    double& to_double() { 
        switch(CurType) {
        //case DoubleType: IntVal = DoubleVal; CurType = IntType; break;
        case IntType: DoubleVal = IntVal; CurType = DoubleType; break;
        }
        return DoubleVal; 
    }
    const double to_double() const { 
        switch(CurType) {
        case DoubleType: return (double)DoubleVal;
        case IntType: return (double)IntVal;
        }
    }
};

void primitive_increment(int& n) {
    ++n;
}

int main() {
    Number pi(3.1415);
    primitive_increment(pi.to_int());
    //pi now is 4
    return 0;
}

I will admit this is quite awkward, and not the ideal situation, but it solves the given problem.

最佳男配角 2024-12-21 12:36:58

而不是将其提供给primitive_increment。您应该为 Number 类重载 ++ 运算符并以这种方式递增它。

Number& operator++() { ++val; return *this;}
Number& operator+=(const Number& rhs) { val += rhs.Val; return *this;}
Number operator+(const Number& rhs) { Number t(*this); t+=rhs; return t;}

请参阅:C 和 C++ 中的运算符

Instead of providing it to primitive_increment. You should overload the ++ operator for your Number class and increment it that way.

Number& operator++() { ++val; return *this;}
Number& operator+=(const Number& rhs) { val += rhs.Val; return *this;}
Number operator+(const Number& rhs) { Number t(*this); t+=rhs; return t;}

see: Operators in C and C++

温柔戏命师 2024-12-21 12:36:58

如果您的 Number 类没有实现 int 的子集,您就不能这样做。例如,如果您的 Number 类包含值 INT_MAX 并且也可以保存值 INT_MAX+1,则会给出错误的结果。如果您的 Number 类模拟了 int 的子集,那么转换为 int 并返回当然是一种选择。

除此之外,您唯一的机会是重写函数以接受 Number 对象。理想情况下将其作为模板,以便它可以与 intNumber 一起使用(以及与任何其他当前或未来提供 int< 的类一起使用) /code> 类似接口)。

If your Number class does not implement a subset of int, you just cannot do that. It would give wrong results if e.g. your Number class contains the value INT_MAX and can hold the value INT_MAX+1 as well. If your Number class models a subset of int, then conversion to int and back is of course an option.

Other than that, your only chance is to rewrite the function to accept Number objects. Ideally make it a template, so that it can work both with int and with Number (as well as with any other current or future class which presents an int-like interface).

じ违心 2024-12-21 12:36:58

将转换运算符设为私有,并让友元函数在其中执行转换。

class silly_wrapper {
private:
  int foo;
  float bar;
  operator int&() { return foo; }

  template <typename T>
  friend void primitive_increment(T& x) { ++static_cast<int&>(x); }
};


int main()
{
   silly_wrapper x;
   primitive_increment(x); // works

   int i;
   primitive_increment(i); // works

   int& r = static_cast<int&>(x); // can't convert - operator is private
}

Make the conversion operator private and have a friend function do the conversion inside of it.

class silly_wrapper {
private:
  int foo;
  float bar;
  operator int&() { return foo; }

  template <typename T>
  friend void primitive_increment(T& x) { ++static_cast<int&>(x); }
};


int main()
{
   silly_wrapper x;
   primitive_increment(x); // works

   int i;
   primitive_increment(i); // works

   int& r = static_cast<int&>(x); // can't convert - operator is private
}
一袭白衣梦中忆 2024-12-21 12:36:58

这是我刚刚想到的一个更奇怪的答案:

class Number; 
template<class par, class base>
class NumberProxy {
    base Val;
    par* parent;
    NumberProxy(par* p, base v) :parent(p), Val(v) {}
    NumberProxy(const NumberProxy& rhs) :parent(rhs.parent), Val(rhs.Val) {}
    ~NumberProxy() { *parent = Val; }
    NumberProxy& operator=(const NumberProxy& rhs) {Val = rhs.Val; return *this}
    operator base& {return Val;}
};

class Number {
private:
    double val;
public:
    Number(int n) : val(n) { }
    Number(float n) : val(n) { }
    Number(double n) : val(n) { }
    // Assume copy constructors and assignment operators exist        
    int to_int() const { return (int) val; }
    float to_float() const { return (float) val; }
    double to_double() const { return val; }

    NumberProxy<Number,int> to_int() { return NumberProxy<Number,int>(this,val); }
    NumberProxy<Number,float> to_float() { return NumberProxy<Number,float>(this,val); }
    NumberProxy<Number,double> to_double() { return NumberProxy<Number,double>(this,val); }
};

void primitive_increment(int& n) {
    ++n;
}

int main() {
    Number pi(3.1415);
    primitive_increment(pi.to_int());
    //pi now is 4
    return 0;
}

Number.to_int() 返回一个 NumberProxy,它可以隐式转换为 int& code>,函数对其进行操作。当函数和表达式完成时,临时 NumberProxy 将被销毁,并且它的析构函数会使用更新后的值更新其父 Number。这带来了额外的便利,只需要对 Number 类进行少量修改。

显然这里存在一些危险,如果您在同一个语句中调用 to_N() 两次,则两个 int& 不会同步,或者如果有人获取 int& ,则两个 int& 不会同步。超过了声明的结尾。

Here's an even more bizzare answer I just thought of:

class Number; 
template<class par, class base>
class NumberProxy {
    base Val;
    par* parent;
    NumberProxy(par* p, base v) :parent(p), Val(v) {}
    NumberProxy(const NumberProxy& rhs) :parent(rhs.parent), Val(rhs.Val) {}
    ~NumberProxy() { *parent = Val; }
    NumberProxy& operator=(const NumberProxy& rhs) {Val = rhs.Val; return *this}
    operator base& {return Val;}
};

class Number {
private:
    double val;
public:
    Number(int n) : val(n) { }
    Number(float n) : val(n) { }
    Number(double n) : val(n) { }
    // Assume copy constructors and assignment operators exist        
    int to_int() const { return (int) val; }
    float to_float() const { return (float) val; }
    double to_double() const { return val; }

    NumberProxy<Number,int> to_int() { return NumberProxy<Number,int>(this,val); }
    NumberProxy<Number,float> to_float() { return NumberProxy<Number,float>(this,val); }
    NumberProxy<Number,double> to_double() { return NumberProxy<Number,double>(this,val); }
};

void primitive_increment(int& n) {
    ++n;
}

int main() {
    Number pi(3.1415);
    primitive_increment(pi.to_int());
    //pi now is 4
    return 0;
}

Number.to_int() returns a NumberProxy<int>, which is implicity convertable to an int&, which the function operates on. When the function and expression complete, the temporary NumberProxy<int> is destroyed, and it's destructor updates it's parent Number with the updated value. This has the added convenience of only requiring minor modification to the Number class.

Obviously theres's some danger here, if you call to_N() twice in the same statement, the two int&'s wont be in sync, or if someone takes a int& past the end of the statement.

抱猫软卧 2024-12-21 12:36:58

(这有点盲目,因为我不完全确定您的整体设计如何组合在一起。)

模板化的自由函数怎么样:

class IncTagIntegral{};
class IncTagNonintegral{};
template <bool> struct IncTag { typedef IncTagNonintegral type; }
template <> struct IncTag<true> { typedef IncTagIntegral type; }

template <typename T> void inc_impl(T & x, IncTagIntegral)
{
  ++x;
}

template <typename T> void inc_impl(T & x, IncTagNonintegral)
{
  x += T(1);
}


template <typename T> void primitive_increment(T & x)
{
  inc_impl<T>(x, typename IncTag<std::is_integral<T>::value>::type());
}

template <> void primitive_increment(Number & x)
{
  // whatever
}

这种方法可能可以推广到您需要将两者应用于现有类型的其他函数以及你自己的类型。


这是另一个长镜头,这次使用类型擦除:

struct TEBase
{
   virtual void inc() = 0;
}

struct any
{
  template <typename T> any(const T &);
  void inc() { impl->inc(); }
private:
  TEBase * impl;
};

template <typename T> struct TEImpl : public TEBase
{
  virtual void inc() { /* implement */ }
  // ...
}; // and provide specializations!

template <typename T> any::any<T>(const T & t) : impl(new TEImpl<T>(t)) { }

关键是您通过专门化的方式提供 TEImpl::inc() 的不同具体实现,但您可以使用 a .inc() 用于 any 类型的 any 对象 a。您可以根据这个想法构建额外的自由函数包装器,例如 void inc(any & a) { a.inc(); }。

(This is a bit of a shot in the dark, as I'm not entirely sure how your overall design fits together.)

How about templated free functions:

class IncTagIntegral{};
class IncTagNonintegral{};
template <bool> struct IncTag { typedef IncTagNonintegral type; }
template <> struct IncTag<true> { typedef IncTagIntegral type; }

template <typename T> void inc_impl(T & x, IncTagIntegral)
{
  ++x;
}

template <typename T> void inc_impl(T & x, IncTagNonintegral)
{
  x += T(1);
}


template <typename T> void primitive_increment(T & x)
{
  inc_impl<T>(x, typename IncTag<std::is_integral<T>::value>::type());
}

template <> void primitive_increment(Number & x)
{
  // whatever
}

This approach may be generalizable to other functions that you need to apply both to existing types and to your own types.


Here's another long shot, this time using type erasure:

struct TEBase
{
   virtual void inc() = 0;
}

struct any
{
  template <typename T> any(const T &);
  void inc() { impl->inc(); }
private:
  TEBase * impl;
};

template <typename T> struct TEImpl : public TEBase
{
  virtual void inc() { /* implement */ }
  // ...
}; // and provide specializations!

template <typename T> any::any<T>(const T & t) : impl(new TEImpl<T>(t)) { }

The key is that you provide different concrete implementations of TEImpl<T>::inc() by means of specialization, but you can use a.inc() for any object a of type any. You can build additional free-function wrappers on this idea, like void inc(any & a) { a.inc(); }.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文