如何解决如何定义具有两个相对参数的模板函数
我正在尝试定义一个函数,它允许我们调用标准哈希函数或一些自定义函数,并返回哈希值。
这是一个关于如何使用我的函数的例子:
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
是一个类模板,而不是一个函数。您可以使用模板模板参数:
#include <cstdint>
#include <functional>
#include <iostream>
#include <string>
template<typename T,template<typename> typename H = std::hash>
std::size_t myfunc(const T &t)
{
return H<T>{}(t);
}
int main() {
std::cout << myfunc(std::string{"123"});
}
不过,要在您的 customHasher
中使用相同的内容,它也需要是一个类模板(带有 operator()
)。
注意需要在main
中显式构造一个字符串,否则无法推导出T
为std::string
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。