简体   繁体   English

c ++模板化的Functor

[英]c++ Templated Functor

Hi guys I'm new to c++ and I've a question regarding templated functor, I'm creating a simple templated functor on my own but just wondering why the value it returns is always "1" when i try to add two values together. 大家好我是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

Also, you need 另外,你需要

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

See Here 看到这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM