0

I don't want to declare the return value two times, so maybe there is a more clever way in modern C++ to do this, but I couldn't find any way.

So, instead of this:

int calculate() {
    int ret=0;
    return ret;
}

I want to do something like this:

int calculate() {
    decltype(return_type) ret=0;
    return ret;
}

It would make it easier to change the return type if needed.

If it's not possible, then why is it not possible?

8
  • 4
    auto calculate() ? Jun 18, 2022 at 11:26
  • 1
    or decltype(auto) calculate()
    – Ted Lyngmo
    Jun 18, 2022 at 11:26
  • 2
    decltype(calculate()) ret = 0;? Jun 18, 2022 at 11:28
  • 2
    @user17732522 I was thinking about the original function (the top one). decltype(auto) should be fine there, no?
    – Ted Lyngmo
    Jun 18, 2022 at 11:32
  • 1
    @TedLyngmo Oh sorry, yes decltype's special rule for directly naming variables is also applied in that case. Still, usually decltype(auto) is dangerous if you don't want the function to be forwarding references, e.g. return(ret); does cause the issue I referred to. Jun 18, 2022 at 11:38

0

Browse other questions tagged or ask your own question.