4
static_assert(
  std::is_convertible<decltype(std::declval<T>() != nullptr), bool>::value,
  "T cannot be compared to nullptr.");

Source: https://github.com/microsoft/GSL/blob/master/include/gsl/pointers

Specifically:

  1. What would the result of decltype(std::declval<T>() != nullptr) be, if T really cannot not be compared to nullptr?
  2. Can I replace != with == here?
  3. Can I replace std::is_convertible with std::is_same here?
1
  • I would expect that, if T really cannot be compared to nullptr, that std::declval<T>() != nullptr would be a diagnosable error. Commented Jan 24, 2021 at 4:08

1 Answer 1

2

If T cannot be compared to nullptr, the whole thing is ill-formed.

https://godbolt.org/z/eqehez

#include <type_traits>

template<typename T>
void foo()
{
    static_assert(
              std::is_convertible<decltype(std::declval<T>() != nullptr), bool>::value,
              "T cannot be compared to nullptr.");
}

int main()
{
    foo<int>();
}

This results in a compiler diagnostic, and not an assertion, using Microsoft's own compiler:

example.cpp
<source>(7): error C2446: '!=': no conversion from 'nullptr' to 'T'
        with
        [
            T=int
        ]
<source>(7): note: A native nullptr can only be converted to bool or, using reinterpret_cast, to an integral type
<source>(13): note: see reference to function template instantiation 'void foo<int>(void)' being compiled
<source>(7): error C2955: 'std::is_convertible': use of class template requires template argument list
C:/data/msvc/14.28.29333/include\type_traits(354): note: see declaration of 'std::is_convertible'
<source>(7): error C2057: expected constant expression
Compiler returned: 2

It doesn't matter whether you use != or == here. Whether you can use is_same is a moot point. This seems to answer the questions you asked. The overall purpose of this static_assert is somewhat unclear. I had a fleeting thought that this might occasionally encounter some evil T that overloads == and != operators for comparing T with std::nullptr_t, which then returns something other than bool. This is a bit of a stretch, but is possible. I looked at that github repo, and that didn't appear to be the case. I think this test is broken.

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

1 Comment

At least, error points into code inside a static_assert That might still help to debug. Without having to create code to detect that operator== exists...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.