我已经为我正在使用的自定义类型创建了一个哈希器类,但它有一个带有参数的构造函数。我无法弄清楚在 unordered_set 中使用它的语法。
class Hasher {
unsigned arg;
public:
Hasher(unsigned a) : arg(a) {}
size_t operator()(const MyType& t) const {
return calculate_hash(arg, t);
}
}
int main() {
unordered_set<MyType, Hasher(2)> myset; // compilation error
}
错误信息:
In file included from Tetrahedron.cc:5:
./Triangulation.h:52:29: error: template argument for template type parameter must be a type
unordered_set<TetraFace,FaceHasher(2)> faces2;
^~~~~~~~~~~~~
/bin/../lib/gcc/x86_64-redhat-linux/6.3.1/../../../../include/c++/6.3.1/bits/unordered_set.h:90:11: note: template parameter is declared here
class _Hash = hash<_Value>,
^
我也尝试过
unordered_set<MyType, Hasher> myset(Hasher(2));
但我仍然收到错误:
In file included from Tetrahedron.cc:5:
./Triangulation.h:52:59: error: expected ')'
unordered_set<TetraFace,FaceHasher> faces2(FaceHasher(2));
^
./Triangulation.h:52:58: note: to match this '('
unordered_set<TetraFace,FaceHasher> faces2(FaceHasher(2));
^
最佳答案
由于您尝试将 Hasher 类型的对象(即实例)作为模板参数传递,因此您会遇到编译错误。
就像您的错误描述的那样:模板类型参数的模板参数必须是类型
它需要一个类型,而您正在传递一个值。
在类型级别参数化 arg。
template<unsigned A>
class Hasher {
unsigned arg = A;
public:
size_t operator()(const int& t) const {
std::cout << arg << std::endl;
return 0;
}
};
int main() {
std::unordered_set<int, Hasher<2>> myset;
myset.insert(5); // prints 2
std::unordered_set<int, Hasher<3>> myset2;
myset2.insert(3); // prints 3
}
关于c++ - 在 C++ 中将参数传递给 unordered_set 哈希函数的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41641929/