[英]Class derived from std::map does not compile on Visual C++ (but compiles on gcc and clang)
I'm writing some container class that wraps std::map. 我正在写一些包装std :: map的容器类。 A simplified version if it is: 如果是以下情况,则为简化版本:
#include <map>
template <typename key_type, typename value_type>
class map2 : private std::map<key_type, value_type>
{
public:
void update(const key_type& key, value_type value)
{
(*this)[key] = std::move(value);
}
};
int main()
{
map2<int, int> m;
m.update(1,4);
}
This code compiles just fine on gcc and clang, but on Visual C++ (I tested the 2015 version and whatever is used on http://rextester.com/l/cpp_online_compiler_visual ) it fails with: 这段代码可以在gcc和clang上很好地编译,但是在Visual C ++上(我测试了2015版以及http://rextester.com/l/cpp_online_compiler_visual上使用的任何版本),它会失败并显示:
source_file.cpp(16): error C2664: 'void map2<int,int>::update(const int &,std::pair<const _Kty,_Ty>)': cannot convert argument 2 from 'int' to 'std::pair<const _Kty,_Ty>'
with
[
_Kty=int,
_Ty=int
]
source_file.cpp(16): note: No constructor could take the source type, or constructor overload resolution was ambiguous
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64
So Visual C++ somehow assumes that the value
parameter of map2::update() is of type std::pair<key_type, value_type>
and not of value_type
. 因此,Visual C ++以某种方式假定map2 :: update()的value
参数类型为std::pair<key_type, value_type>
而不是value_type
。 But why is it doing that, while gcc and clang accept my code just fine? 但是为什么在gcc和clang接受我的代码很好的情况下这样做呢?
The problem is likely what Visual C++ is not doing, and that's two-phase name lookup. 问题可能出在Visual C ++ 没有做的事情上,而这是两阶段的名称查找。 Since there's only one phase of name lookup, it will have to look up value_type
in that phase. 由于只有一个阶段的名称查找,因此必须在该阶段查找value_type
。 And as a hack, VC++ then already looks into dependent base classes such as std::map<key_type, value_type>
here. 而且,作为一种技巧,VC ++现在已经在这里查找依赖的基类,例如std::map<key_type, value_type>
。
This incorrectly finds std::map<K, V>::value_type
, a typedef for pair<K,V>
. 这会错误地找到std::map<K, V>::value_type
, pair<K,V>
。 This explains the VC++ error message. 这说明了VC ++错误消息。
Workaround: Disambiguate the argument name in map2
yourself. 解决方法:自己消除map2
的参数名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.