简体   繁体   中英

Using std::optional in a C++11 context

I'm writing a small C++11 library in which I believe std::optional would be a nice addition in some functions which can return nullptr . However, std::optional is a C++17 feature. Since being C++11 is a requirement, I'm looking for ways to use std::optional while keeping compatibility.

I found that feature macros can be tested. I suppose I could use it to detect whether std::optional is available... but what's the best approach when it isn't?

Should I provide my own std::optional implementation?

Return nullptr when std::optional isn't available? (Likely to mess my code.)

Or give up on the idea and keep returning nullptr only?

There is no standard way of using std::optional in C++11. You can either depend on C++17, or you cannot use std::optional .

Should I provide my own std::optional implementation?

You can write your own optional implementation, but you cannot call it std::optional . Alternatively, you can use a pre-existing implementation such as the one in Boost.

All that said, if you're returning a pointer anyway, then there is probably not much point in using optional since pointers already have a representation for "empty" value: the null pointer. If however you need to distinguish null from empty, then optional may be useful.

use this header: https://github.com/TartanLlama/optional

It is the equivalent of std::optional. But it works on C++11 also. When you upgrade to C++17, switch your code to #include <optional> .

You should not make return type dependent on C++ Standard version. Standard version switches are meant to be able to compile different parts of a program with different values. If you behave differently based on this, you'll break ODR.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM