I have a code that works like this:
template<size_t size> struct myClass { public: std::array<uint8_t, size> bytes; bool operator==(const myClass<size>& o) const { for (size_t i{0}; i < size; ++i) { if (bytes[i] != o.bytes[i]) return false; } return true; } uint8_t& operator[] (size_t ind) { return bytes[ind]; } const uint8_t& operator[] (size_t ind) const { return bytes[ind]; // function body is identical, can I write only once? } }; int main() { myClass<4> my{23,24,55,26}; my.bytes[2] = 24; cout << std::dec << static_cast<int32_t>(my[2]) << endl; my[2] = 44; cout << static_cast<int32_t>(my[2]) << endl; uint8_t *p1 = &my[2]; cout << static_cast<int32_t>(*p1) << endl; const myClass<4> my2{23,24,55,26}; const uint8_t *p2 = &my2[2]; cout << static_cast<int32_t>(*p2++) << endl; cout << static_cast<int32_t>(*p2) << endl; return 0;} My question is that, the uint8_t& operator[](size_t ind){} and const uint8_t& operator[](size_t ind) const {} have identical function body of return bytes[ind];. Therefore, I need to write identical code for two times. Is there a method that I only write the function body for once, and also make the code work?