How does C++ trailing return type help in virtual functions?

82 views Asked by At

There is a statement in C++ Hight Performance book:

The trailing return is necessary in some contexts. For example, if we are writing a virtual function, or the function declaration is put in a header file and the function definition is in a .cpp file.

How does trailing return type help in those two cases? Cannot find anything about that.

1

There are 1 answers

0
Artyer On

The trailing return type can lookup inside the class whereas the leading return type would be in the namespace scope for the out-of-class definition of a member function.

For example:

struct S {
    using type = int;
    type f();
};

type S::f() {  // Error: type not declared in this scope
}

// You need: `S::type S::f() {}`

auto S::f() -> type {  // OK: finds S::type
}

If your return type is very complicated (usually templated and dependent), you might be forced to use a trailing return type, e.g.:

template<typename T>
struct S {
    template<typename U>
    static U g();

    decltype(g<T>()) f();
};

template<typename T>
decltype(S<T>::template g<T>()) S<T>::f() {  // Error: does not match
}

template<typename T>
auto S<T>::f() -> decltype(g<T>()) {  // OK
}

These are an example for the second half of the quote "or the function declaration is put in a header file and the function definition is in a .cpp file".

There should be no difference between a virtual and a non-virtual member function's use of a trailing return type. Though virtual functions typically do have an out-of-line declaration, so maybe that's what it is referring to?