C++ overload operator twice, one return non-const reference and the other const reference, what is the preference?

后端 未结 3 1704
遥遥无期
遥遥无期 2021-02-05 15:06

I overload an operator twice with the same parameter list. but with different return type:

T& operator()(par_list){blablabla}    
const T& operator()(par         


        
3条回答
  •  执笔经年
    2021-02-05 15:23

    You can't overload a function/method based on return type. I would expect the compiler to throw an error here. What you can do is specify the method itself as a const method, using

    const T& operator()(par_list) const {blahblah}
    

    The const qualifier not only means this can be called on a const receiver, but it also is used in the overload resolution. This happens because it affects the implicit *this parameter that's passed to the method; a const method uses a const qualifier on *this, and const qualifiers are taken into account during overload resolution.

提交回复
热议问题