c++ - 在 C++ 中将参数传递给 unordered_set 哈希函数的语法

标签 c++ syntax clang++ unordered-set

我已经为我正在使用的自定义类型创建了一个哈希器类,但它有一个带有参数的构造函数。我无法弄清楚在 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/

相关文章:

c++ - 将 boost::transform_iterator 与非常量仿函数一起使用

C++ 不可能的指针行为

c++ - 为什么结构数组的大小在传递给函数时会发生变化?

main 之外的 C++ 对象初始化

bash - 理解 bash 中的 $' ' 引号

gcc - 如何指示 gcc/clang 将临时文件输出到特定目录

c++ - Clang 搜索路径文件

c++ - 在 clang 中使用别名模板时,有没有办法缩短模板化类名?

python - 语法错误: no ascii character input operation

javascript - 是什么决定了一个 JavaScript 函数是一个命名的匿名函数还是一个,嗯,常规函数?