Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is decltype necessary in an "auto returning" function?

Consider this code :

#include <iostream>
#include <typeinfo>

using namespace std;

template<typename T1, typename T2>
auto add(T1 l, T2 r) -> decltype(l + r){
    return l + r;
}

class C {};

class B {};

class A {
public:
    C operator+(const B& b) {
        C c;
        return c;
    }
};


int main() {
    // Using add()
    A a;
    B b;
    auto c = add(a, b);

    cout << typeid(a).name() << endl;
    cout << typeid(b).name() << endl;
    cout << typeid(c).name() << endl;
    cout << endl;

    // Doing the same thing but not on a function
    A a2;
    B b2;
    auto c2 = a2 + b2;

    cout << typeid(a2).name() << endl;
    cout << typeid(b2).name() << endl;
    cout << typeid(c2).name() << endl;
}

I just have a very simple question: why do I need to put decltype() in the postfix return type of add() unlike in the second method (the one that doesn't use add())?

like image 960
Mark Garcia Avatar asked Jun 27 '26 08:06

Mark Garcia


2 Answers

why do I need to put decltype() in the postfix return type of add() unlike in the second method (the one that doesn't use add())?

Because that's part of the rules of C++. The parser is run left-to-right; for the most part, if an identifier hasn't been reached yet, the parser doesn't know about it. Identifiers like the function parameters.

So if you use an expression to determine the type of the return value, and that expression uses the parameters in some way, you must put the return type after the function arguments.

But my point is, why can't the compiler automatically deduce the return type when it knows that A + B returns C?

Because those are the rules of C++: a function must have a return type specified directly in the function declaration. The compiler isn't allowed to deduce it.

Yet.

like image 182
Nicol Bolas Avatar answered Jun 28 '26 20:06

Nicol Bolas


why do I need to put decltype() in the postfix return type of add()

Because you declared the return type of the template function as auto, and you need to specify somehow the return type after function's declaration.

You could have also specified it like this :

auto add(T1 l, T2 r) -> C

but that wouldn't work very well if you pass for example integers to that function.

I do not see the 2nd add function, but if you mean operator+, then you specified the return type for it.

like image 30
BЈовић Avatar answered Jun 28 '26 21:06

BЈовић



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!