Reputation: 17138
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. What's the problem?
Upvotes: 1
Views: 438
Reputation: 139900
You can only overload operators with at least one user-defined type as an argument. Neither int
nor int*
are user-defined types.
Upvotes: 6
Reputation: 70048
As already mentioned in other answers that you cannot have operator !=
for non userdefined types like int
, char
and so on.
One option is to wrap int
inside your user defined struct
and achieve the goal.
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;
Upvotes: 2