C++ 尾随返回类型对虚函数有何帮助?

问题描述 投票:0回答:1

C++ Hight Performance书中有这样的说法:

在某些情况下尾随返回是必要的。例如,如果我们正在编写一个虚函数,或者函数声明放在头文件中,函数定义放在 .cpp 文件中。

尾随返回类型在这两种情况下有何帮助? 找不到任何相关内容。

c++ virtual-functions trailing-return-type
1个回答
0
投票

尾随返回类型可以在类内部查找,而前导返回类型将在成员函数的类外定义的命名空间范围内。

例如:

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

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

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

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

如果您的返回类型非常复杂(通常是模板化和依赖的),您可能被迫使用尾随返回类型,例如:

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
}

这些是引用后半部分的示例“或者函数声明放在头文件中,函数定义放在 .cpp 文件中”。

虚拟和非虚拟成员函数对尾随返回类型的使用应该没有区别。虽然虚函数通常确实有一个外线声明,所以也许这就是它所指的?

© www.soinside.com 2019 - 2024. All rights reserved.