模板化操作符过载技巧

时间:2011-07-26 12:10:36

标签: c++ templates operator-overloading

有没有办法通过使用一些元编程技巧制作这样的情况:

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())
{
    ///

}

关键是我不想改变这一行k!= get()但由于某种原因我的操作员!=似乎不起作用。有什么问题?

3 个答案:

答案 0 :(得分:6)

您只能使用至少一个用户定义类型作为参数重载运算符。 intint*都不是用户定义的类型。

答案 1 :(得分:3)

您不能为内置类型重载运算符。

答案 2 :(得分:2)

正如其他答案中已经提到的那样,对于非operator !=int等非用户定义类型,您无法char

一种选择是将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;
  }
};

现在宣布

Int k = 1;
相关问题