原始数据类型的包装类
在设计解决方案时,有时为原始数据类型提供包装类可能会很方便。考虑一个表示数值的类,可以是 double
、float
或 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; }
};
现在假设我有一个这样的函数:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
C++11 具有显式运算符重载。
C++11 has explicit operator overloads.
我承认这很尴尬,而且不是理想的情况,但它解决了给定的问题。
I will admit this is quite awkward, and not the ideal situation, but it solves the given problem.
而不是将其提供给
primitive_increment
。您应该为Number
类重载 ++ 运算符并以这种方式递增它。请参阅:C 和 C++ 中的运算符
Instead of providing it to
primitive_increment
. You should overload the ++ operator for yourNumber
class and increment it that way.see: Operators in C and C++
如果您的
Number
类没有实现int
的子集,您就不能这样做。例如,如果您的Number
类包含值INT_MAX
并且也可以保存值INT_MAX+1
,则会给出错误的结果。如果您的Number
类模拟了int
的子集,那么转换为int
并返回当然是一种选择。除此之外,您唯一的机会是重写函数以接受
Number
对象。理想情况下将其作为模板,以便它可以与int
和Number
一起使用(以及与任何其他当前或未来提供int< 的类一起使用) /code> 类似接口)。
If your
Number
class does not implement a subset ofint
, you just cannot do that. It would give wrong results if e.g. yourNumber
class contains the valueINT_MAX
and can hold the valueINT_MAX+1
as well. If yourNumber
class models a subset ofint
, then conversion toint
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 withint
and withNumber
(as well as with any other current or future class which presents anint
-like interface).将转换运算符设为私有,并让友元函数在其中执行转换。
Make the conversion operator private and have a friend function do the conversion inside of it.
这是我刚刚想到的一个更奇怪的答案:
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:
Number.to_int()
returns aNumberProxy<int>
, which is implicity convertable to anint&
, which the function operates on. When the function and expression complete, the temporaryNumberProxy<int>
is destroyed, and it's destructor updates it's parentNumber
with the updated value. This has the added convenience of only requiring minor modification to theNumber
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.(这有点盲目,因为我不完全确定您的整体设计如何组合在一起。)
模板化的自由函数怎么样:
这种方法可能可以推广到您需要将两者应用于现有类型的其他函数以及你自己的类型。
这是另一个长镜头,这次使用类型擦除:
关键是您通过专门化的方式提供
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:
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:
The key is that you provide different concrete implementations of
TEImpl<T>::inc()
by means of specialization, but you can usea.inc()
for any objecta
of typeany
. You can build additional free-function wrappers on this idea, likevoid inc(any & a) { a.inc(); }
.