2

I am having a mixed C++14/C++17 codebase and I want to enable a function isEmpty only if I am having std::optional at hand. So, I tried SFINAE:

template <typename T, typename int_<decltype(std::nullopt)>::type = 0>
inline bool isEmpty(const std::optional<T>& v) {
  return !v;
}

However, that doesn't work.

How can I conditionally compile isEmpty if std::optional is there?

user3612643
  • 5,096
  • 7
  • 34
  • 55

1 Answers1

5

If your compiler is recent enough (e.g. GCC >= 9.1 or Clang >= 9.0.0), you may include header <version> and conditionally compile your function template if macro __cpp_lib_optional is defined:

#include <version> // provides, among others, __cpp_lib_optional

#ifdef __cpp_lib_optional
template <typename T>
inline bool isEmpty(const std::optional<T>& v) {
    return !v;
}
#endif

This way, isEmpty will only be compiled if you're in -std=c++17 mode (or higher).

user3612643
  • 5,096
  • 7
  • 34
  • 55
paolo
  • 2,345
  • 1
  • 3
  • 17
  • For Visual Studio this would be `#if _HAS_CXX17`. – Spencer Jun 07 '22 at 16:38
  • Don't forget to wrap `#include ` inside a conditional block, too. Either inside the shown `#ifdef __cpp_lib_optional` block, or inside of its own `#ifdef __has_header #if __has_header() #include #endif #endif` block – Remy Lebeau Jun 07 '22 at 17:37