Elegant Solution to Duplicate Getters for Const and Non-Const Objects
When dealing with getters in C , developers often encounter the dilemma of having to create separate implementations for const and non-const versions. This can be inconvenient when the logic for both getters is largely similar.
One potential solution to this issue is to implement the non-const version by casting away the const from the const version. This approach is considered safe because the calling function is non-const, which implies that the object itself is non-const, allowing for the conversion.
For instance:
class Foo { public: const int& get() const { //non-trivial work return foo; } int& get() { return const_cast<int&>(const_cast<const Foo*>(this)->get()); } };
This approach may not be aesthetically pleasing, but it guarantees safety and avoids the need for separate implementations in many cases. It allows developers to focus on the core functionality of the getters rather than duplicating code.
The above is the detailed content of How Can I Avoid Duplicate Getters for Const and Non-Const Member Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!