2

How can I #define a type that has a double colon in C++?

For example, I want to include the std::optional type from the std library. The code bellow won't work because the compiler cannot parse the double colon in #define my_namespace::optional.

#if __cplusplus >= 201703L // C++17
#include <optional>
#define my_namespace::optional std::optional
#else
#include <my_optional.h>
#define my_namespace::optional my_namespace::my_optional
#endif

// Use the optional type
my_namespace::optional<int32_t> some_value;
Anon
  • 69
  • 4
  • 3
    You simply can't. – R Sahu Apr 16 '18 at 04:22
  • 3
    You possibly want a [namespace alias](http://en.cppreference.com/w/cpp/language/namespace_alias). – Jonathan Potter Apr 16 '18 at 04:23
  • 1
    The answer you’re looking for seems to be different than the duplicate. You want to declare `namespace my_namespace{ using my_optional = std::optional; }` In general, use macros only when you have to. (One example: error messages with the filename and line number that crashed the program.) – Davislor Apr 16 '18 at 04:24
  • You might want to check out [my question on Code Review](https://codereview.stackexchange.com/q/136350/49895) – Justin Apr 16 '18 at 04:31
  • 1
    Guys, I think an answer about how to do this without preprocessor macros is more helpful than giving a negative answer about macros? – Davislor Apr 16 '18 at 04:31
  • @Davislor, good suggestion. I'll unclose. – R Sahu Apr 16 '18 at 04:33

1 Answers1

2

The answer (thanks to Davislor):

#if __cplusplus >= 201703L // C++17
#include <optional>
namespace my_namespace
{
    template<class T>
    using optional = std::optional<T>;
}
#else
#include <my_optional.h>
namespace my_namespace
{
    template<class T>
    using optional = my_optional<T>;
}
#endif
Anon
  • 69
  • 4