Here is a classic example of a class with two getters for its fields:
class point
{
int x_, y_;
public:
point(int x, int y) : x_(x), y_(y) {}
int x() const
{
return x_;
}
int y() const
{
return y_;
}
};
int main()
{
point p(1, 2);
std::cout << p.x() << ", " << p.y() << '\n';
}
One could argue that printing a point to an output stream should really be provided by an overload of operator<<
, but let's suppose that a client wants to print in his own favorite format or do something completely different with x and y. Then he clearly needs to get to the x and y fields somehow, right?
A basic principle of object-oriented programming is "tell, don't ask". That is, ideally I should tell my object to do something with the x and y fields instead of asking for them. That led me to the following idea:
class point
{
int x_, y_;
public:
point(int x, int y) : x_(x), y_(y) {}
template<typename Fun>
void operator()(Fun fun) const
{
fun(x_, y_);
}
};
int main()
{
point p(3, 4);
p([](int x, int y){
std::cout << x << ", " << y << '\n';
});
}
This would have been too clumsy in C++98, but now that we have lambdas, it seems feasible to me. Is this approach actually more sound than the first version with the getters, or am I a bit too enthusiastic?
What do you think? How widely applicable is it? Is there something I'm missing? Could it be improved?
fun(x_, y_);
line, and clients would still work. – fredoverflow Dec 10 '11 at 9:36z_
variable. Suddenly every lambda which performs printing would have to be updated to include this extra point. The abstraction that you are providing of "call an arbitrary function with my fields" is not a particularly useful one. A better way might be to present some sort of tuple interface to "Fields that should be printed", and then to have printers/formatters work off that abstraction. – Mankarse Dec 10 '11 at 9:43