Customized error message for deleted function use

94 Views Asked by At

Let's say I have a noncopyable class and I want to provide a customized error message when users try to copy.

struct A {
    A() = default;

private:
    [[deprecated("customized message")]]
    A(const A&);

    [[deprecated("customized message")]]
    A& operator=(const A&);
};

I cannot use =delete for them, because compiler would only complain they are deleted. So I tried the transitional way: private non-defined functions.

Compiler will show

warning: 'A::A(const A&)' is deprecated: customized message [-Wdeprecated-declarations]

It works but not that good, because the word deprecated sounds like allowed-but-discouraged rather than disallowed simply.

My another try is

struct Customized_Message {
    Customized_Message() = default;
    Customized_Message(const Customized_Message&) = delete;
    Customized_Message& operator=(const Customized_Message&) = delete;
};
struct A : Customized_Message {
    A() = default;
};
<source>:17:11: error: use of deleted function 'A::A(const A&)'
   17 |     A b = a;
      |           ^
<source>:11:8: note: 'A::A(const A&)' is implicitly deleted because the default definition would be ill-formed:
   11 | struct A : Customized_Message {
      |        ^
<source>:11:8: error: use of deleted function 'Customized_Message::Customized_Message(const Customized_Message&)'
<source>:8:5: note: declared here
    8 |     Customized_Message(const Customized_Message&) = delete;
      |     ^~~~~~~~~~~~~~~~~~

It works but looks not elegant ([Edit] because the message is not short, and compiler will replicate it as above).

Is there a better way to provide a customized error message? Thank you.

0

There are 0 best solutions below