kadina
kadina

Reputation: 5376

Where trailing return type is actually needed in C++?

I am reading about trailing return type. I came across this site https://blog.petrzemek.net/2017/01/17/pros-and-cons-of-alternative-function-syntax-in-cpp/ which is explaining about the need of these return types and it mentioned as below.

template<typename Lhs, typename Rhs>
decltype(lhs + rhs) add(const Lhs& lhs, const Rhs& rhs) {
    // error: ^^^ 'lhs' and 'rhs' were not declared in this scope
    return lhs + rhs;
}

... Since the compiler parses the source code from left to right, it sees lhs and rhs before their definitions, and rejects the code. By using the trailing return type, we can circumvent this limitation.

But as per my understanding, by the time compiler reaches decltype(lhs + rhs), it should already know the types of lhs and rhs. Can any one please let me know why compiler is not able to deduce the return types of the function and are there any other uses where we must use trailing return type other than templates.

Upvotes: 2

Views: 281

Answers (1)

John Kugelman
John Kugelman

Reputation: 361595

It knows the capitalized types Lhs and Rhs, but not the lowercase variables lhs and rhs. They're declared after the decltype.

Upvotes: 5

Related Questions