为什么包含任意STL头解决了这些编译错误?

goo*_*ion 4 c++ stl

我的程序中有这个全局函数:

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

它给了我以下编译错误:

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
Run Code Online (Sandbox Code Playgroud)

我可以通过在函数体之前包含任意STL头来解决它,例如:

#include <string>
static bool IsValidType(const CString& cType)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

但当然,我认为这不是正确的做法.

你可以向我解释一下为什么包含一个任意的STL头可以解决这个问题,以及我应该如何正确地解决它?

谢谢.

tas*_*oor 8

由于您使用的是initializer_list,因此您应该包括initializer_list.

#include <initializer_list>
Run Code Online (Sandbox Code Playgroud)

包括string解决错误string可能包括initializer_list,但那种间接包含不是推荐的方式.


use*_*042 4

您能否向我解释一下为什么包含任意 STL 标头可以解决此问题,

因为许多标准标头在其实现中包含其他标头。

我应该如何正确解决它?

包括专用于包含这些缺失的函数/类型的标头。
在您的情况下,根据文档<iterator>,这是,标头。<initializer_list>