onqtam
onqtam

Reputation: 4548

deleted functions with a compile time message when they are used

So I'm trying to restrict operations on a type that has a conversion operator to bool - for example:

template <typename R>
Result
operator&&(const R&) {
    STATIC_ASSERT(false, MY_MESSAGE);
    return Result();
}

STATIC_ASSERT is my wrapper macro around c++11 static_assert and a macro-ish c++98 static assert.

I want a somewhat useful message as an error for users that try to use this so making it private or deleting it in c++11 aren't an option.

This however works only for MSVC because of the difference between msvc and g++/clang - with g++/clang the static assert always fires - even when the "deleted" function is not used.

The only thing I've seen that would do the trick is to use an undefined type with it's name as the message as the return type of the template - like this:

template<typename R>
STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison&
operator&&(const R&);

I first saw this here

Is there any other way to do this in c++98 - a deleted function with a custom message when the user tries to use it?

Upvotes: 1

Views: 208

Answers (1)

Jarod42
Jarod42

Reputation: 218268

in static_assert(false, message), false is non dependent of template.

You have to make your condition depending of template.

as static_assert(!std::is_same<T, T>::value, message)

Since p2593r1 (C++23, but retro-actif), static_assert(false) is possible.

Upvotes: 2

Related Questions