[英]Templated operator overload trick
Is there a way to by using some metaprogramming trick make situation like this works: 有没有一种方法可以通过使用一些元编程技巧使这种情况起作用:
int* get();//this fnc returns pointer to int OR nullptr
int k = 1;
//this is the operator which is supposed to compare value and pointer
template<class T>
bool operator!=(const T& left, const T* right)
{
if (right)
{
return left != *right;
}
else
{
return false;
}
}
//And this is the code fragment which interests me most
if (k != get())
{
///
}
The crux is that I would like NOT TO change this line k != get() and yet for some reason my operator!= seems not to work. 症结在于,我不想更改此行k!= get(),但是由于某种原因,我的operator!=似乎无法正常工作。 What's the problem?
有什么问题?
You can only overload operators with at least one user-defined type as an argument. 您只能重载至少一个用户定义类型作为参数的运算符。 Neither
int
nor int*
are user-defined types. int
和int*
都不是用户定义的类型。
您不能为内置类型重载运算符。
As already mentioned in other answers that you cannot have operator !=
for non userdefined types like int
, char
and so on. 正如其他答案中已经提到的那样,您不能为非用户定义类型(例如
int
, char
等)使用operator !=
。
One option is to wrap int
inside your user defined struct
and achieve the goal. 一种选择是将
int
包装在用户定义的struct
并实现目标。
struct Int
{
int i;
// define all the necessary operators/constructor who deal with 'int'
Int(int x) : i(x) {}
bool operator != (const int* right)
{
return (right)? (i != *right) : false;
}
};
Now declare 现在声明
Int k = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.