mardi 27 octobre 2020

How to introduce a struct in the std namespace

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

Aucun commentaire:

Enregistrer un commentaire