Returning From a Void Function in C++

前端 未结 7 944
再見小時候
再見小時候 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

    Templates:

    template <typename T, typename R>
    R some_kind_of_wrapper(R (*func)(T), T t)
    {
       /* Do something interesting to t */
       return func(t);
    }
    
    int func1(int i) { /* ... */ return i; }
    
    void func2(const std::string& str) { /* ... */ }
    
    int main()
    {
       int i = some_kind_of_wrapper(&func1, 42);
    
       some_kind_of_wrapper(&func2, "Hello, World!");
    
       return 0;
    }
    

    Without being able to return void, the return func(t) in the template would not work when it was asked to wrap func2.

    0 讨论(0)
提交回复
热议问题