Tuesday, April 7, 2026

Reusing code in const and non-const methods, C++17

I found the code below from this great answer in StackOverflow. It allows you to implement the const method with your logic, then use this one-liner to implement the non-const method. It’s a trick from the great Scott Meyers:

T const& f() const {
	return something_complicated();
}

T& f() {
	return const_cast<T&>(std::as_const(*this).f());
}

I’m using this thing everywhere.

No comments:

Post a Comment