1

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?

1
  • @HansPassant thanks. (this was regarding > this < question) Commented Sep 14, 2016 at 10:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Actually I just realized the same thing and came up with a solution of my own - template <typename T> struct deferred_false { static const bool value = false; }; and I pass deferred_false<R>::value to the static assert!
Can you clarify what it means that it's C++23, but retro-active?
Recent compilers (which have C++23 support) should allow static_assert(false), even in C++11 mode.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.