Domanda

virtual void myFunc(int& a, int& b) {}

I get warnings about unused variables but I do not want to do anything with them in the base class. I want the derived classes to implement them if they want, and to do nothing if they do not implement them. What can I do to stop the warnings other than putting a flag on the compiler ?

È stato utile?

Soluzione

Simply don't give them a name:

virtual void myFunc( int&, int& );

Altri suggerimenti

Since you don't want to use them you can emit the parameter names.

However, instead of removing them completely it's sometimes more useful to comment them out like this:

virtual void myFunc(int& /* a */ , int& /* b */ ) 
{
}

This way you can still see what the intent of the parameter was by looking at the commented out name. This is particularly useful if you put the implementation in the header as it will be the only place which mentions the parameter names.

You have several ways to silent this warning:

  • Remove them from declaration/definition:

    virtual void myFunc(int& /* a */ , int& /* b */ ) {}
    

    This solution may provoke some warnings with some tool as Doxygen...

  • Use a trick to tell the argument is unused:

    template <typename T> void unusedArg(const T&) {} // Helper function.
    
    // In the class
    virtual void myFunc(int& a, int& b) { unusedArg(a); unusedArg(b); }
    

    or in C++11:

    template <typename... Ts> void unusedArgs(const Ts&...) {} // Helper function
    
    // In the class
    virtual void myFunc(int& a, int& b) { unusedArgs(a, b); } // C++11
    
  • In C++17, you may also use attribute [[maybe_unused]]:

    // In the class
    virtual void myFunc([[maybe_unused]] int& a, [maybe_unused]] int& b) {}
    

Try to defined the function without names of parameters as

virtual void myFunc(int& ,int&  ) 
{

}

Also consider the possibility tto make the base class abstract

virtual void myFunc(int& a,int& b ) = 0;

if it simply spesifies an interface.

Under some compilers, you can simply write the variable name as a "no-op" statement.

virtual void myFunc(int& a, int& b) 
{
    a;    // unused variable
    b;
}

However, to support other compilers and to make the intent clear, you can use a macro or function unused_argument to make it clear. 

If that does not works with your compiler, I think that doing sizeof(a); would works.

In Qt (5.x and above, maybe even earlier), you have access to the Q_UNUSED macro located in qglobal.h. This macro performs a cast to void of its argument, with the result stored nowhere - and so no side effects other using the variable in a way that MinGW/GCC will find acceptable.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top