#include <iostream>
using namespace std;
class my_vector {
public:
double data[6] = {1,2,3,4,5,6};
double & operator()(size_t i) {
std::cout<<"Calling non-const ()"<<std::endl;
return data[i];
}
double operator()(size_t i) const {
std::cout<<"Calling const ()"<<std::endl;
return data[i];
}
};
void withConst(const my_vector &v) {
double vv = v(0);
std::cout<<"v(0) = "<<vv<<std::endl;
// v(0) = 4.0; // Does not compile
}
void withNonConst(my_vector &v) {
v(0) = 4.0;
double vv = v(0);
std::cout<<"v(0) = "<<vv<<std::endl;
}
int main() {
my_vector vec;
withConst(vec);
withNonConst(vec);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY2xhc3MgbXlfdmVjdG9yIHsKcHVibGljOgoJZG91YmxlIGRhdGFbNl0gPSB7MSwyLDMsNCw1LDZ9OwoJZG91YmxlICYgb3BlcmF0b3IoKShzaXplX3QgaSkgewoJCXN0ZDo6Y291dDw8IkNhbGxpbmcgbm9uLWNvbnN0ICgpIjw8c3RkOjplbmRsOwoJCXJldHVybiBkYXRhW2ldOwoJfQoJZG91YmxlIG9wZXJhdG9yKCkoc2l6ZV90IGkpIGNvbnN0IHsKCQlzdGQ6OmNvdXQ8PCJDYWxsaW5nIGNvbnN0ICgpIjw8c3RkOjplbmRsOwoJCXJldHVybiBkYXRhW2ldOwoJfQp9OwoKdm9pZCB3aXRoQ29uc3QoY29uc3QgbXlfdmVjdG9yICZ2KSB7Cglkb3VibGUgdnYgPSB2KDApOwoJc3RkOjpjb3V0PDwidigwKSA9ICI8PHZ2PDxzdGQ6OmVuZGw7CgkvLyB2KDApID0gNC4wOyAvLyBEb2VzIG5vdCBjb21waWxlCn0KCnZvaWQgd2l0aE5vbkNvbnN0KG15X3ZlY3RvciAmdikgewoJdigwKSA9IDQuMDsKCWRvdWJsZSB2diA9IHYoMCk7CglzdGQ6OmNvdXQ8PCJ2KDApID0gIjw8dnY8PHN0ZDo6ZW5kbDsKfQoKaW50IG1haW4oKSB7CglteV92ZWN0b3IgdmVjOwoJd2l0aENvbnN0KHZlYyk7Cgl3aXRoTm9uQ29uc3QodmVjKTsKCXJldHVybiAwOwp9