I have this simple example of using a functor in C++:
#include <memory>
#include <ostream>
#include <iostream>
template <typename T>
struct Point {
T x, y;
Point(T x, T y) : x(x), y(y){};
Point(){};
Point<T> operator+(const Point<T>& other) {
this->x += other.x;
this->y += other.y;
return *this;
}
};
template <typename T>
struct AddSome {
AddSome(){};
AddSome(T* what) { add_what = (T)*what; };
AddSome(T what) : add_what(what){};
T operator()(T to_what) {
if (ptr) {
return to_what + add_what;
}
return to_what + add_what;
};
private:
std::shared_ptr<T> ptr;
T add_what;
};
int main(int argc, char* argv[]) {
Point<int>* pt = new Point<int>(5, 6);
AddSome<Point<int>> adder5(pt);
Point<int> test = adder5(*pt);
std::cout << test.x << " " << test.y << std::endl;
return 0;
}
In the version above it works very well but it doesn't work at all if I delete the default constructor of the Point
class.
What does the compiler need this constructor for?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire