C++:相似整数类型的重载运算符
我有一个名为 MyType
的类型,它是一个 int
:
typedef int MyType;
它在整个代码中被视为 int
。
我希望能够分别为 int
和 MyType
重载运算符:
class C
{
public:
C& operator>>(int i) {}
C& operator>>(MyType i) {}
};
但我不能:
overload.cpp:7:7: error: 'C& C::operator>>(MyType)' cannot be overloaded
overload.cpp:6:7: error: with 'C& C::operator>>(int)'
我可以鱼和熊掌兼得吗?
I have a type called MyType
that is an int
:
typedef int MyType;
It gets treated as an int
throughout the code.
I'd like to be able to overload an operator separately for both int
and MyType
:
class C
{
public:
C& operator>>(int i) {}
C& operator>>(MyType i) {}
};
but I can't:
overload.cpp:7:7: error: 'C& C::operator>>(MyType)' cannot be overloaded
overload.cpp:6:7: error: with 'C& C::operator>>(int)'
Can I have my cake and eat it too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像往常一样,您需要一个强大的 typedef。其一种实现是
BOOST_STRONG_TYPEDEF
。As per usual, you need a strong typedef. One implementation of that is
BOOST_STRONG_TYPEDEF
.正如@Cat++所说,BOOST_STRONG_TYPEDEF是一个很好的解决方案。然而,对于那些不想依赖 boost 库的人(如果你这样做的话,没有错误),这样做更容易:
用法:
TYPEDEF(int, MyType);
So What这个宏可以吗?
这个宏基本上创建了一个新的结构,可以在很多方面很容易地被视为原始类型。对于编译器来说,这是一种完全不同的类型。
以您的
MyType
为例。当您将其声明为typedef int MyType;
时,在编译时,MyType
会被int
替换。而且由于您已经有一个使用int
作为参数定义的函数,因此它会抱怨重复的函数体。当您执行 TYPEDEF(int, MyType); 时,MyType 是一个可以初始化并分配 int 类型值的结构,并且会被编译器视为与 int 完全不同的数据类型。然而,由于
operator =
函数,您将能够为其分配int
值,并由于其将其值检索为
和int
Operator const Original_type&() constoperator Original_type&()
函数。这大致就是 boost 对其
BOOST_STRONG_TYPEDEF
宏所做的事情,但它似乎是从其他内部类继承的,我不确定这些类的作用。但对于那些出于某种原因不想依赖Boost的人来说,这是一个粗略的解决方案。我的个人建议:尽可能使用Boost。
As @Cat++ said, BOOST_STRONG_TYPEDEF is a good solution. However for those who don't want to rely on boost library (no mistake if you do) it is easier to do it this way:
Usage:
TYPEDEF(int, MyType);
So What Does this Macro Do?
This macro basically creates a new structure that can easily be treated as the original type in many ways. And to the compiler this is a totally different type.
Take your
MyType
for instance. When you declare it astypedef int MyType;
, at compile time,MyType
gets replaced byint
. And since you already have a function defined withint
as the parameter, it would complain about duplicate function body.When you do
TYPEDEF(int, MyType);
, MyType is a structure that can be initialized and assigned a value of int type and would be treated by the compiler as a totally different data-type from int. Yet you will be able to assign itint
values because of theoperator =
function and retrieve its value as anint
because of itsoperator const original_type&() const
andoperator original_type&()
functions.This roughly what boost does with its
BOOST_STRONG_TYPEDEF
macro but it seems to be inheriting from other internal classes and I'm not sure what those classes does. But this is a crude solution for those who don't want to rely on boost for whatever reason.My Personal Recommendation: Use boost whenever possible.