请考虑以下代码段:
void Foo()
{
// ...
}
void Bar()
{
return Foo();
}
Run Code Online (Sandbox Code Playgroud)
在C++中使用上述内容的正当理由是什么,而不是更常见的方法:
void Foo()
{
// ...
}
void Bar()
{
Foo();
// no more expressions -- i.e., implicit return here
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*sop 16
在您的示例中可能没用,但在某些情况下,void在模板代码中很难处理,我希望这个规则有时会对此有所帮助.非常做作的例子:
#include <iostream>
template <typename T>
T retval() {
return T();
}
template <>
void retval() {
return;
}
template <>
int retval() {
return 23;
}
template <typename T>
T do_something() {
std::cout << "doing something\n";
}
template <typename T>
T do_something_and_return() {
do_something<T>();
return retval<T>();
}
int main() {
std::cout << do_something_and_return<int>() << "\n";
std::cout << do_something_and_return<void*>() << "\n";
do_something_and_return<void>();
}
Run Code Online (Sandbox Code Playgroud)
请注意,只main需要处理这样一个事实:在void没有任何东西可以从中返回的情况下retval.中间函数do_something_and_return是通用的.
当然,这只是让你至今-如果do_something_and_return希望,在正常情况下,存储retval在一个变量并在返回之前用它做的东西,那么你还是会遇到麻烦-你有专攻(或过载)do_something_and_return的无效.
您可以在通用代码中使用它,其中Foo()的返回值未知或可能会更改.考虑:
template<typename Foo, typename T> T Bar(Foo f) {
return f();
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,Bar对void有效,但如果返回类型更改也有效.但是,如果它只是调用f,那么如果T是非空的,那么这个代码就会破坏.使用return f(); 语法保证保存Foo()的返回值(如果存在),并允许void().
此外,明确返回是一个很好的习惯.