简体   繁体   中英

How do I call overloaded member function with cv-qualifier?

I have been reading through the C++ standard and from there I found out that the cv-qualifiers are part of the function signature for member functions.

Consider the case below:

/******************************
* Function signature testing
*******************************/
class Signature
{   
public:
    void vSignature( void )
    {
        cout << "signature" << endl;        
    }

    void vSignature( void ) const 
    {
        cout << "constant signature" << endl;
    }
};

typedef void (Signature::*constFunc)( void ) const ;
int main(void)
{
    constFunc f = &Signature::vSignature;
    Signature s;
    s.vSignature();  //outputs 'signature'
    (s.*f)();        // outputs 'constant signature'
    return 0;
}

In the above code, when I call vSignature in the 'ordinary' way, the non-const overload gets called. In order to 'force' the const overload to be used, I have to obtain the pointer to the vSignature function and cast it to the const overload.

Is there any other way to call the vSignature() const overload aside from the above?

Is there any other way to call the vSignature() const overload aside from the above?

Yes. You can do this:

//first 
const Signature s;
s.vSignature(); //calls const function

//second
Signature s;
static_cast<const Signature &>(s).vSignature(); //calls const function

 //third
 void f(const Signature &s)
 { 
      s.vSignature(); //calls const function
 }

 Signature s;
 f(s);

The idea is : const functions get invoked on const object and const expression involving the object.

Not really. In any case, the cv-qualified version of a function should do the exact same thing as the non cv-qualified version, but should just be there for the sake of const-correctness.

据我了解,const成员函数仅在const对象上调用,因此,如果您的对象是非const,它将调用非const函数。

如果调用该函数的对象是const则将调用所需的函数:

((const Signature&)s).vSignature();

The overload chosen depends on the type of the expression, not the underlying type of the object. Therefore you can just add the const with a cast:

const_cast<Signature const&>(s).vSignature();

This has the added advantage that the reader can easily spot what you're doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM