Daniel F
Daniel F

Reputation: 283

Determine the return value type of a function inside itself

To the best of my knowledge, the C++ core language currently does not provide a general functionality to determine the return value type of a function inside of itself, such as:

auto f(std::uint8_t value)
{
    double result {0.0};
    // ...
    auto&& tmp = static_cast<decltype(return)>(value);
    // ...
    return result;
}

Why does a feature like decltype(return) not yet exist? Would it be justified to have the wish that it be added to the core language?

Upvotes: 0

Views: 95

Answers (2)

Enlico
Enlico

Reputation: 28374

You are returning result, so the type that auto will deduce (at compile time) is the type of result.

As suggested in the comment, the type deduced by auto is not the same as the one that decltype(result) would deduce, in general, as they behave differently: auto uses template type deducion, whereas decltype does this. Therefore they can differ in the reference-ness of the deduced type, which can be quite important.

In your example, however, since result is an unparenthesized id-expression, decltype(result) will deduce just double, and the return auto will deduce the same, so probably this is fine. You decide.

auto f(std::uint8_t value)
{
    double result {0.0};
    // lots of code ..
    auto&& tmp = static_cast<decltype(result)>(value);
    // lots of code ...
    return result;
}

Once the program is compiled, the return type of f is the type of result, and this cannot change whatsoever, therefore there's no need to have the syntax support decltype(return).

The point is that regardless of the complexity of the case you consider, once you are able to compile the program, that means that the compiler is able to determine all the types it needs. It can be hard for humans to find out what the return type is (and many other template things, honestly), but not for compilers. Or, better, it's not hard nor easy for the compiler to deduce the types: it either does (and then you can run the program) or it doesn't (and it fails at compile time).

Upvotes: 3

eerorika
eerorika

Reputation: 238301

Enrico's answer shows how to do what you need.

To answer the question:

Why does a feature like decltype(return) does not yet exist?

Either because such feature hasn't been proposed, or because such proposal hasn't been accepted into the language.

Upvotes: 2

Related Questions