What are helper functions in C++?

后端 未结 4 797
难免孤独
难免孤独 2021-01-31 09:50

I was trying to understand helper functions in C++ from The C++ Programming Language by Bjarne Stroustrup. But the book hasn\'t explained anything about it and the

4条回答
  •  走了就别回头了
    2021-01-31 10:21

    "helper function" is not a term that you would find in a standard, neither it has an exact definition... standard mentions "helper class" or "helper template" few times to refer to a class, which is not meant to be instantiated by end-users but it provides an useful functionality internally used within another class.

    Helper functions are (what I believe the most people mean when they say it) usually functions that wrap some useful functionality that you're going to reuse, most likely over and over again. You can create helper functions meant to be used for many different kinds of purposes...

    An example might be conversion function of any kind, for example function converting multi-byte encoded std::string to std::wstring:

    std::wstring s2ws(const std::string& str)
    {
        int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
        std::wstring wstrTo( size_needed, 0 );
        MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
        return wstrTo;
    }
    

提交回复
热议问题