Const and Non-Const Getters: An Elegant Solution
Overloaded getters with const and non-const variants present a programming conundrum. Directly implementing one from the other results in compilation errors, forcing developers to resort to casting. Is there a more graceful approach?
The Challenge
Consider the following class with getSomething methods:
class Foobar { public: Something& getSomething(int index); const Something& getSomething(int index) const; };
Implementing one method using the other is not feasible due to the inability of the const version to call the non-const version. Casting is necessary, but it feels cumbersome and can lead to confusion.
The Solution: Cast with Caution
Effective C suggests casting away the const from the const function to implement the non-const function. While not visually appealing, it is a safe approach. Since the non-const member function is being called, the object must be non-const, and casting away the const is permissible.
Here's an example:
class Foo { public: const int& get() const; int& get(); }; const int& Foo::get() const { // Non-trivial work return foo; } int& Foo::get() { return const_cast<int&>(const_cast<const Foo*>(this)->get()); }
By following this approach, you can achieve type-safe const and non-const getter implementations without sacrificing performance or introducing unnecessary complexity.
The above is the detailed content of Const vs. Non-Const Getters: Is There a Better Way Than Casting?. For more information, please follow other related articles on the PHP Chinese website!