简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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