mardi 22 décembre 2015

Inferring return types with `-> decltype`

When using the C++11 arrow decltype statement, why does boost::optional::operator*() behave differently than boost::optional::get()?

Here's my code.

template<typename Fun, typename... Xs>
auto repeat_remove_optional(Fun f, std::string prompt, Xs&&... xs)
    -> decltype(f(prompt, xs...).get())
{
    auto x = f(prompt, xs...);
    if (x) return *x;
    prompt += "(Required!) ";
    while (true) {
        x = f(prompt, xs...);
        if (x) return *x;
    }
}

Use case is on some functions that prompt user with string and return boost::none if they enter escape during the input.

Using -> decltype(*f(prompt, xs...)) won't compile, saying that rvalue reference to type 'bool' cannot bind to lvalue of type 'bool': if (x) return *x; (at both return statements there is this error).

In other places in my code, the two functions behave identically. Why does this change here?

Aucun commentaire:

Enregistrer un commentaire