std::map 成员编译器错误的大括号初始化
Braced initialisation of std::map member compiler error
以下代码不使用 Visual Studio 2013 编译。它使用 Xcode 6.1 (Clang 3.5) 编译。
std::string s1("one");
std::string s2("two");
std::string s3("three");
std::string s4("four");
class X
{
typedef std::map<std::string, std::string> MyMapType;
MyMapType map1 = { { s1, s2 }, { s3, s4 } };
MyMapType map2 = { { std::make_pair(s1, s2) }, { std::make_pair(s3, s4) } };
};
两个声明报告的错误是:
error C2664: 'std::map<std::string,std::string,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>::map(std::initializer_list<std::pair<const _Kty,_Ty>>,const std::less<_Ty> &,const std::allocator<std::pair<const _Kty,_Ty>> &)' : cannot convert argument 2 from 'initializer-list' to 'const std::allocator<std::pair<const _Kty,_Ty>> &'
但是,下面的编译:
int main()
{
typedef std::map<std::string, std::string> MyMapType;
MyMapType map3 = { { s1, s2 }, { s3, s4 } };
return 0;
}
谁能解释一下。
众所周知,Visual C++ 2013 在处理非静态数据成员初始值设定项和构造函数成员初始值设定项列表中的列表初始化时存在问题。它被严重破坏 - 在某些情况下导致无声的错误代码生成 - 他们只是在 Visual 中的所有情况下将其设为编译器错误
Studio 2013 Update 3(提供实际修复 was apparently deemed too risky for an update)。
您的代码可以在 Microsoft's online compiler 上正常编译,它运行 Visual C++ 2015 的预览版,所以看起来这个问题已得到修复。
一种变通方法(在上面链接的 MSDN 页面中注明)也在 RHS 上明确指定类型,这样您实际上并不是在列表初始化非静态数据成员。
MyMapType map1 = MyMapType{ { s1, s2 }, { s3, s4 } };
MyMapType map2 = MyMapType{ { std::make_pair(s1, s2) }, { std::make_pair(s3, s4) } };
以下代码不使用 Visual Studio 2013 编译。它使用 Xcode 6.1 (Clang 3.5) 编译。
std::string s1("one");
std::string s2("two");
std::string s3("three");
std::string s4("four");
class X
{
typedef std::map<std::string, std::string> MyMapType;
MyMapType map1 = { { s1, s2 }, { s3, s4 } };
MyMapType map2 = { { std::make_pair(s1, s2) }, { std::make_pair(s3, s4) } };
};
两个声明报告的错误是:
error C2664: 'std::map<std::string,std::string,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>::map(std::initializer_list<std::pair<const _Kty,_Ty>>,const std::less<_Ty> &,const std::allocator<std::pair<const _Kty,_Ty>> &)' : cannot convert argument 2 from 'initializer-list' to 'const std::allocator<std::pair<const _Kty,_Ty>> &'
但是,下面的编译:
int main()
{
typedef std::map<std::string, std::string> MyMapType;
MyMapType map3 = { { s1, s2 }, { s3, s4 } };
return 0;
}
谁能解释一下。
众所周知,Visual C++ 2013 在处理非静态数据成员初始值设定项和构造函数成员初始值设定项列表中的列表初始化时存在问题。它被严重破坏 - 在某些情况下导致无声的错误代码生成 - 他们只是在 Visual 中的所有情况下将其设为编译器错误 Studio 2013 Update 3(提供实际修复 was apparently deemed too risky for an update)。
您的代码可以在 Microsoft's online compiler 上正常编译,它运行 Visual C++ 2015 的预览版,所以看起来这个问题已得到修复。
一种变通方法(在上面链接的 MSDN 页面中注明)也在 RHS 上明确指定类型,这样您实际上并不是在列表初始化非静态数据成员。
MyMapType map1 = MyMapType{ { s1, s2 }, { s3, s4 } };
MyMapType map2 = MyMapType{ { std::make_pair(s1, s2) }, { std::make_pair(s3, s4) } };