c++模板函数

c++ Templated Functor

本文关键字:函数 c++      更新时间:2023-10-16

大家好,我是c++的新手,我有一个关于模板函子的问题,我正在自己创建一个简单的模板函子,但我只是想知道为什么当我尝试将两个值相加时,它返回的值总是"1"。

class AddValue{
private:
    int x;
public:
    template <class T, class U> 
    bool operator() (const T &v1, const U &v2)
    {   
        x = v1 + v2;
        return x;
    }
};
int main(){
    AddValue addvalue;
    int a = 3;
    int b = 6;
    cout<< addvalue(a, b) << endl;
    return 0;
}
  bool operator() (const T &v1, const U &v2) // You're returning bool
//^^ should be T

此外,您需要

  T operator() (const T &v1, const U &v2)
    {   
        T x = v1 + v2; // Notice x type as T
        return x;
    }

请参阅此处