#Reduce reused code in class member const overloads?

15 messages · Page 1 of 1 (latest)

wet panther
#
[[nodiscard]] int& top(const int idx) noexcept { 
        assert(!isTopEdge(idx));
        return matrixData[topIndex(idx)]; 
    }
    [[nodiscard]] int top(const int idx) const noexcept {
        assert(!isTopEdge(idx));
        return matrixData[topIndex(idx)];
    }

In this scenario, the only differentiating factor is the function signature, it is implicitly determined whether the return value is going to be by value or reference based on the function signature, and one of them is const.

Is there any way that I could reduce the copied code by possibly using templates? Can I create a generic method, and then create two prototypes of it, one using a reference and one without, and make the one without the reference const?

ashen iceBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

red shard
wet panther
red shard
#

oh wait I missed the top one is a int&

wet panther
#

yep, returns by ref

daring inlet
wet panther
# daring inlet But `matrixData` and `topIndex` seems to be accessible anyway. What prevents yo...

I should have posted the whole code, it is inside a class where it is accessible, it is my fault for thinking that it was implied.
https://pastebin.com/x2e8dxtq
Too big for discord, but you can see the amount of reused code and the member variables that are in scope

devout mist
#

I'd just rename it, the compiler isnt smart enough to do const by default and only borrow mutably if required

#

also what happens if you ask for an out of bounds index? does assert call std::abort? would it be a better idea to return a std::expected<T, OutOfRange>? where struct OutOfRange {} is a unit struct?

wet panther
devout mist
#

fair, just thought i'd mention it because it looks like you're being thorough putting [[nodiscard]], const and noexcept on things.

ashen iceBOT
#

@wet panther Has your question been resolved? If so, run !solved :)

wet panther
#

I suppose it isn't officially supported then, thanks for all the answers.

#

!solved