使用 std::tuple 作为 std::unordered_map 的键
使用下面的代码,我在 MSVC 中遇到了一个非常令人困惑的错误,它似乎表明密钥类型(std::tuple)正在转换为 std::string.
With the code below, I get a very confusing error in MSVC that seems to suggest the key type (an std::tuple) is being converted to an std::string.
#include <iostream>
#include <string>
#include <tuple>
#include <utility>
#include <unordered_map>
typedef std::tuple<std::string,int,char> key_t;
struct key_hash : public std::unary_function<key_t, std::size_t>
{
std::size_t operator()(const key_t& k) const
{
return std::get<0>(k)[0] ^ std::get<1>(k) ^ std::get<2>(k);
}
};
struct key_equal : public std::binary_function<key_t, key_t, bool>
{
bool operator()(const key_t& v0, const key_t& v1) const
{
return (
std::get<0>(v0) == std::get<0>(v1) &&
std::get<1>(v0) == std::get<1>(v1) &&
std::get<2>(v0) == std::get<2>(v1)
);
}
};
struct data
{
std::string x;
};
typedef std::unordered_map<key_t,data,key_hash,key_equal> map_t;
int main()
{
map_t m;
data d;
d.x = "test data";
m[std::make_tuple("abc",1,'X')] = d;
auto itr = m.find(std::make_tuple(std::string("abc"),1,'X'));
if (m.end() != itr)
{
std::cout << "x: " << itr->second.x;
}
return 0;
}
错误:
Error 1 error C2664: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string(const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 1 from 'const std::tr1::tuple<_Arg0,_Arg1,_Arg2>' to 'const std::basic_string<_Elem,_Traits,_Ax> &' c:Program Files (x86)Microsoft Visual Studio 10.0VCinclude uple 127 1
编译器:MS Visual Studio 2010
Compiler: MS Visual Studio 2010
在 ideone 上,我得到以下更令人费解的错误:
On ideone, I get the following even more convoluted error:
http://ideone.com/yEv2j
我似乎想不通我哪里出错了.
I can't seem to figure out where I've gone wrong.
推荐答案
ideone 的问题是 key_t
已经存在:
The problem for ideone is that key_t
already exists:
prog.cpp:7:42: error: conflicting declaration 'typedef class std::tuple<std::basic_string<char>, int, char> key_t'
/usr/include/sys/types.h:123:17: error: 'key_t' has a previous declaration as 'typedef __key_t key_t'
将您的 key_t
重命名为其他名称,或将其放入某些命名空间.
Rename your key_t
to something else, or put it into some namespaces.
此更改后您的代码在 g++ 和 clang++ 中都有效.我相信这是 MSVC 中的一个错误.
Your code works after this change in both g++ and clang++. I believe this is a bug in MSVC.
相关文章