Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does including an arbitrary STL header resolves these compilation errors?

Tags:

c++

stl

I have this global function in my program:

static bool IsValidType(const CString& cType)
{
    for (auto pType : {"bmp","jpg","jpeg","gif","tif","tiff","png"})
        if (cType == CString(pType))
            return true;
    return false;
}

And it gives me the following compilation errors:

error C3312: no callable 'begin' function found for type 'initializer-list'
error C3312: no callable 'end' function found for type 'initializer-list'
error C2065: 'pType' : undeclared identifier

I can resolve it by including an arbitrary STL header before the function body, for example:

#include <string>
static bool IsValidType(const CString& cType)
{
    ...
}

But of course, I don't think that this is the correct way to do it.

Can you please explain to me why including an arbitrary STL header resolves this problem, and how I should go about resolving it correctly?

Thank you.

like image 339
goodvibration Avatar asked Aug 13 '17 10:08

goodvibration


3 Answers

Since you are using initializer_list you should include initializer_list.

#include <initializer_list>

Including string resolve the error as string probably includes initializer_list, but that kind of indirect include is not the recommended way.

like image 161
taskinoor Avatar answered Oct 14 '22 00:10

taskinoor


Can you please explain to me why including an arbitrary STL header resolves this problem,

Because many standard headers include other ones in their implementation.

and how I should go about resolving it correctly?

Include the headers that are dedicated to contain these missing functions/types.
In your case that is the <iterator>, <initializer_list> header according to the documentation.

like image 23
user0042 Avatar answered Oct 14 '22 00:10

user0042


Not an arbitrary STL header.

If you look at the definitions of std::begin and std::end in the standard, it says: (in [iterator.container]/p1):

1 In addition to being available via inclusion of the <iterator> header, the function templates in 27.8 are available when any of the following headers are included: <array>, <deque>, <forward_list>, <list>,<map>, <regex>, <set>, <string>, <unordered_map>, <unordered_set>, and <vector>.

Amusingly enough, <string_view> is not on that list.

  • There's an existing defect report report about that.
  • libc++, at least, does define std::begin and std::end if you include <string_view>.
like image 42
Marshall Clow Avatar answered Oct 14 '22 01:10

Marshall Clow