从C ++中的void函数返回 [英] Returning From a Void Function in C++

查看:181
本文介绍了从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\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>();
}

请注意,只有 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 for 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函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆