【发布时间】:2021-03-29 08:46:56
【问题描述】:
我正在尝试定义一个函数,它允许我们调用标准哈希函数或一些自定义函数,并返回哈希值。
这是一个关于如何使用我的函数的示例:
auto res = myfunc<std::hash>(2); //hash the integer 2 with the function std::hash
auto res2 = myfunc<std::hash>("abc"); // hash the string "abc" with the function std::hash
auto res3 = myfunc<customHasher>(2); // hash the integer 2 with some custom hash function
我尝试编写如下代码:
template<void (*T)(U)>
size_t myfunc(const U &u)
{
return T<U>(u);
}
T应该是函数指针,std::function或者lambda,U是T的参数类型。
但是无法编译。
main.cpp:14:23: error: expected ‘>’ before ‘(’ token
template<void (*T)(U)>
^
main.cpp:15:25: error: ‘U’ does not name a type
size_t myfunc(const U &u)
^
main.cpp: In function ‘size_t myfunc(const int&)’:
main.cpp:17:18: error: ‘U’ was not declared in this scope
return T<U>(u);
好吧,我知道template<void (*T)(U)> 一定是错误的,因为U 没有定义。但我不知道如何解决它。
【问题讨论】:
-
std::hash不是函数。修复你对函数指针的尝试(假设它是可能的)仍然不会让你走得更远。 -
@StoryTeller-UnslanderMonica 好的,我在帖子中添加了一行:“T 应该是函数指针、std::function 或 lambda,U 是 T 的参数类型。” .
-
customhasher是模板吗?return T<U>(u);建议T是一个模板,这是否需要或者你可以通过例如std::hash<int>吗? -
@largest_prime_is_463035818 是的,customhasher 就像
std::hash一样,是一个参数的模板。 -
@largest_prime_is_463035818 这就是重点。你看,我不想传递
std::hash<int>,我只想简单传递一个std::hash。