简体   繁体   English

如何使用两个相关参数定义模板 function

[英]How to define a template function with two relative parameters

I'm trying to define a function, which allows us to call the standard hash function or some custom-defined function, and return the value of hash. I'm trying to define a function, which allows us to call the standard hash function or some custom-defined function, and return the value of hash.

Here is an example about how to use my function:这是一个关于如何使用我的 function 的示例:

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

I've tried to code as below:我尝试编写如下代码:

template<void (*T)(U)>
size_t myfunc(const U &u)
{
    return T<U>(u);
}

T should be a function pointer, a std::function or a lambda, and U is the type of parameter of T . T应该是 function 指针、 std::function或 lambda, UT的参数类型。

But it can't be compiled.但是不能编译。

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);

Well, I know that template<void (*T)(U)> must be wrong because U is not defined.好吧,我知道template<void (*T)(U)>一定是错误的,因为U没有定义。 But I don't know how to fix it.但我不知道如何解决它。

You need to declare both parameters.您需要声明这两个参数。 Moreover, std::hash is a class template, not a function.此外, std::hash是 class 模板,而不是 function。 You can use a template template parameter:您可以使用模板模板参数:

#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"});
}

Though, to use the same with your customHasher it needs to be a class template (with operator() ), too.不过,要与您的customHasher一起使用,它也需要是一个 class 模板(带有operator() )。

Note that you need to explicitly construct a string in main , otherwise T cannot be deduced to be std::string .请注意,您需要在main中显式构造一个字符串,否则T不能被推断为std::string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM