How to introduce a struct in the std namespace

Viewed 107

We currently use C++11. std::optional is missing from C++11 - it has been introduced in C++17. Luckily, I found an implementation which has the same interface as std::optional and works in C++11 (https://github.com/TartanLlama/optional)

This defines optional in namespace tl. So, I can use it like so:

#include "optional.hpp"

tl::optional<int> to_int(string str) {
    if (...) { return atoi(str); } 
    else     { return tl::nullopt; }
} 

However, I am looking for a way to call this as if std::optional was available:

#include "optional.hpp"

std::optional<int> to_int(string str) {
    if (...) { return atoi(str); } 
    else     { return std::nullopt; }
} 

This way, when we switch to C++17, I will not have to replace each tl::optional with std::optional. I will only have to replace the contents of the "optional.hpp" header with:

// optional.hpp 
// ------------
#include <optional.hpp>

Today, this header is implemented as:

// optional.hpp 
// ------------
#include "tl/optional.hpp"   // include the official header, when C++17 is available

How can I create some sort of an alias in this header, so that when I call std::optional it will actually refer to the tl::optional ?

  • I cannot touch the original code of tl/optional.hpp.
  • I would prefer not to use a macro
1 Answers

How to introduce a struct in the std namespace

By writing a proposal to the standards committee. But in this case the class is already adopted, so what you need to do to get the class is start using the new version of the standard.

How can I create some sort of an alias in this header, so that when I call std::optional it will actually refer to the tl::optional ?

As not-the-standard-library-implementer, you are not allowed to introduce classes into the std namespace.

What you can have instead, is an alias in your own namespace:

namespace my_very_own {
    using tl::optional; // change to std::optional when possible
}
Related