Skip to content

Instantly share code, notes, and snippets.

@gagolews
Last active November 19, 2020 20:55
Show Gist options
  • Save gagolews/9206364 to your computer and use it in GitHub Desktop.
Save gagolews/9206364 to your computer and use it in GitHub Desktop.
operator() for structs in C++
#include <iostream>
#include <vector>
using namespace std;
// an illustration for my Julia-related question on julia-users
struct datfun {
// some data
vector<double> x;
vector<double> y;
// operator() lets the object act like a function;
// note that here we operate on the object's fields
// (one function, different "hidden" input data)
vector<double> operator()(int i) {
vector<double> ret(2);
ret[0] = x[i];
ret[1] = y[i];
return ret;
}
datfun(const vector<double>& _x, const vector<double>& _y) { // auxiliary
x = _x; y = _y;
}
};
ostream& operator<<(ostream& out, const vector<double>& v) { // auxiliary
for (int i=0; i<v.size(); ++i)
out << v[i] << " ";
out << endl;
}
int main() {
// example vectors:
vector<double> x1(10), y1(10), x2(10), y2(10);
for (int i=0; i<10; ++i) {
x1[i] = i+1;
y1[i] = 10*(i+1);
x2[i] = -x1[i];
y2[i] = -y1[i];
}
// create two objects:
datfun f1(x1, y1);
datfun f2(x2, y2);
// and now:
cout << f1(1); // 2 20
cout << f2(1); // -2 -20
x1[1] = 1000;
cout << f1(1); // 2 20 (no change -> deep copy)
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment