Returning From a Void Function in C++(从 C++ 中的 void 函数返回)
问题描述
考虑以下代码段:
void Foo()
{
// ...
}
void Bar()
{
return Foo();
}
在 C++ 中使用上述方法而不是更常见的方法的正当理由是什么:
What is a legitimate reason to use the above in C++ as opposed to the more common approach:
void Foo()
{
// ...
}
void Bar()
{
Foo();
// no more expressions -- i.e., implicit return here
}
推荐答案
在你的例子中可能没有用,但是在模板代码中有一些情况很难处理 void,我希望这条规则有时会有所帮助.非常人为的例子:
Probably no use in your example, but there are some situations where it's difficult to deal with void in template code, and I expect this rule helps with that sometimes. Very contrived example:
#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
";
}
template <typename T>
T do_something_and_return() {
do_something<T>();
return retval<T>();
}
int main() {
std::cout << do_something_and_return<int>() << "
";
std::cout << do_something_and_return<void*>() << "
";
do_something_and_return<void>();
}
请注意,只有 main 必须处理在 void 情况下没有什么可以从 retval 返回的事实.中间函数 do_something_and_return 是通用的.
Note that only main has to cope with the fact that in the void case there's nothing to return from retval . The intermediate function do_something_and_return is generic.
当然,这只能让你到目前为止 - 如果 do_something_and_return 在正常情况下想要将 retval 存储在一个变量中并在返回之前对其执行一些操作,那么你仍然会遇到麻烦 - 你必须专门化(或重载)do_something_and_return 为 void.
Of course this only gets you so far - if do_something_and_return wanted, in the normal case, to store retval in a variable and do something with it before returning, then you'd still be in trouble - you'd have to specialize (or overload) do_something_and_return for void.
这篇关于从 C++ 中的 void 函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C++ 中的 void 函数返回
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
