我有一个简单的类,我想为其重载运算符,如下所示

class MyClass
{
   public:
      int first;

      template <typename T>
      T operator () () const { return first; }
};

还有我的其他地方
MyClass obj;

int i = obj(); // This gives me an error saying could not deduce
               // template argument for T

有人可以帮助我解决这个错误,非常感谢。谢谢。

编辑:

这与operator()有关,例如,如果我将函数替换为
    template <typename T>
    T get() const { return first;}

有用。感谢所有回应。

最佳答案

如果您希望函数调用是隐式的,则必须将模板应用于此类:

template <typename T>
class MyClass
{
  public:
  T first;

  T operator () () const { return first; }
};

如果应将其强制转换为其他类型,则应为:
template <typename T>
class MyClass
{
  public:
  T first;

  template <typename U>
  U operator () () const { return (U)first; }
};

关于c++ - 模板C++的operator()重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/992272/

10-12 07:25
查看更多