Results differ based on type when parsing a std::optional<T> with default_value std::nullopt
When writing to a `std::optional<T>`, CLI11 has different behavior when writing a `std::nullopt` as the `.default_val()` depending on the type.
In this example, having `std::nullopt` as the default for a `std::optional<int>` works as expected (after parsing and using the default, the variable has no value). However, when writing to a `std::optional<std::string>`, the empty string `""` is written to the variable, resulting in the optional having an assigned value.
```c++
#include "CLI11.hpp"
#include <optional>
int main(int argc, char** argv)
{
CLI::App app{"Example"};
std::optional<int> a;
app.add_option("-a", a)
->default_val(std::nullopt);
std::optional<std::string> b;
app.add_option("-b", b)
->default_val(std::nullopt);
CLI11_PARSE(app, argc, argv);
std::cout << "a: " << (a.has_value() ? std::to_string(a.value()) : "std::nullopt") << std::endl;
std::cout << "b: " << (b.has_value() ? b.value() : "std::nullopt") << std::endl;
if(b.has_value()){
std::cout << b.value().size() << " " << b.value() << " " << (b == "") << std::endl;
}
}
```
Compile:
```sh
g++ -std=c++17 optional.cpp -o optional
```
Run
```
# Note: nothing passed in, so the defaults are used
./optional
```
Output:
```
a: std::nullopt
b:
0 1
```
Ideally, there would be a uniform behavior when writing a `std::nullopt` as a default value.
0 条评论