Alon
Alon

Reputation: 1804

c++ how to create my own warning in compilation time

I want to create my own warning in compilation time and not in pre-processor (as I've seen a few answers to) Let's say we have:

class A
{
private:
    explicit A(A const& other);
};

now if the user does:

A first;

and then:

A second(first);

he'll get an error that copy constructed is not implemented or whatever.. bare in mind that my code has a lot of inheritances in it... as well as referring me to the H file A is implemented in and not where I tried to use copy constructor...

so.. instead of the compiler's default warning I'd like to create my own.... something like.. "You cannot use copy constructor"

Help? Thanks!

Upvotes: 4

Views: 1646

Answers (2)

ForEveR
ForEveR

Reputation: 55887

Without preprocessor, using only standard C++, it's unreal. You can use static_assert, but it's not warning.

Upvotes: 1

TemplateRex
TemplateRex

Reputation: 70506

Using a static_assert with a user-define message will trigger this error message during compilation

class A
{
private:
    A() {}

    explicit A(A const& /* other */) 
    { 
        static_assert(false, "You cannot use copy constructor"); 
    }
};

int main()
{
    A first;    
    A second(first); // compile error
}

Output on LiveWorkSpace

Note this will produce an error and not a warning. However, it is almost always best to use a "warnings as errors" compiler option and to explicity (i.e. documented with a comment) disable warnings that you know are innocuous.

Upvotes: 3

Related Questions