I am currently working on a program in which I encountered an issue (not for the first time) where I have two acessor methods for a data structure. The methods are identical, except one is const and returns a const pointer while the other is non-const and returns a non-const pointer. The code in the methods is non-trivial, making it ideal to not duplicate it between the two methods for all the same reasons that code duplication is bad in general. What is the best way to solve this issue?
The only reasonable-seeming idea that I have is this, but I am not entirely convinced that this is best because 1) I am not sure if a const_cast is acceptable here with regard to undefined behavior and other violations of the C++ standard¹, and 2) I have heard that a const_cast is a sign of bad code.
Node *NodeSet::getNode(int index){
const Node *node = static_cast<const NodeSet*>(this)->getNode(index);
return const_cast<Node*>(node);
}
const Node *NodeSet::getNode(int index) const{
//non-trivial code to get the correct node
}
¹: It is important to me that I write standard C++ that does not rely on any particular compiler to compile and run correctly.
std::as_const()
helps a bit.