Returning From a Void Function in C++

前端 未结 7 942
再見小時候
再見小時候 2020-12-31 11:21

Consider the following snippet:

void Foo()
{
  // ...
}

void Bar()
{
  return Foo();
}

What is a legitimate reason to use the above in C++

7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 12:00

    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 
    
    template 
    T retval() {
        return T();
    }
    
    template <>
    void retval() {
        return;
    }
    
    template <>
    int retval() {
        return 23;
    }
    
    template 
    T do_something() {
        std::cout << "doing something\n";
    }
    
    template 
    T do_something_and_return() {
        do_something();
        return retval();
    }
    
    int main() {
        std::cout << do_something_and_return() << "\n";
        std::cout << do_something_and_return() << "\n";
        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.

    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.

提交回复
热议问题