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())?
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.
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.