Purely suppress gcc `final` warnings (` -Wsuggest-final-types` and `-Wsuggest-final-methods`)

I like to compile my code using -Wsuggest-final-typesand -Wsuggest-final-methodsto get warnings about the possibilities of using a keyword finalso that the compiler can optimize more aggressively.

Sometimes, however, the sentences are incorrect - for example, I have a class Basewith a destructor virtual ~Base()that is used polymorphically in another project, and gcc offers me so that I Basecan mark it as final.

Is there a way to “purely” tell the compiler that it is Baseused polymorphically and should not be marked as final?

The only way I can think of is to use directives #pragma, but I find this makes the code cluttered and hard to read.

Ideally, I am looking for a keyword or attribute non-finalthat can be added / added to a class / method declaration.

+7
source share
1 answer

I came up with a macro solution that I really don't like, but it solves the problem.

#define MARK_NONFINAL_CLASS(base)                              \
    namespace SOME_UNIQUE_NAME                                 \
    {                                                          \
        struct [[unused]] temp_marker final : base             \
        {                                                      \
        };                                                     \
    }

#define MARK_NONFINAL_METHOD(base, return_type, method)                  \
    namespace SOME_UNIQUE_NAME                                           \
    {                                                                    \
        struct [[unused]] temp_marker final : base                       \
        {                                                                \
            inline return_type [[unused]] method override {}             \
        };                                                               \
    }

Using:

class Base
{
    virtual ~Base()
    {
    }

    virtual int a(float f)
    {
    }
    virtual void b(double)
    {
    }
};

MARK_NONFINAL_CLASS(Base)
MARK_NONFINAL_METHOD(Base, int, a(float))
MARK_NONFINAL_METHOD(Base, void, b(double))
+2
source

Source: https://habr.com/ru/post/1628093/


All Articles