[英]How can i make pointer to a template function?
I have a template sort function that takes pointer to another function as a paramater to define sorting rule.我有一个模板排序函数,它将指向另一个函数的指针作为参数来定义排序规则。
template<typename T>
void sort(T* arr, int size, function<bool(T, T)>& comparer);
and i want to call this function with lambda expression我想用 lambda 表达式调用这个函数
sort(arr, size, [](int num1, int num2) { if (num1 > num2) { return true; } else { return false; } });
However i had an error:但是我有一个错误:
Error (active) E0304 no instance of overloaded function "sort" matches the argument list
错误(活动)E0304 没有重载函数“sort”的实例与参数列表匹配
Is there a way to create pointer to template function?有没有办法创建指向模板函数的指针? How can i do this?
我怎样才能做到这一点?
Template argument deduction will try to deduce T
from both the first parameter T* arr
and the third one function<bool(T, T)>& comparer
.模板参数推导将尝试从第一个参数
T* arr
和第三个function<bool(T, T)>& comparer
推导出T
This will fail, because the lambda doesn't actually have type function<bool(T, T)>
for any T
.这将失败,因为 lambda 实际上没有任何
T
类型function<bool(T, T)>
。 (It can only be converted to one.) (它只能转换为一个。)
In function templates function objects are usually taken directly by a template parameter, not as std::function
:在函数模板中,函数对象通常由模板参数直接获取,而不是作为
std::function
:
template<typename T, typename F>
void sort(T* arr, int size, F comparer);
or或者
template<typename T, typename F>
void sort(T* arr, int size, F&& comparer);
depending on whether you want a copy of the function object or just a reference.取决于您是想要函数对象的副本还是只是一个引用。
std::function
explicitly.std::function
。#include <functional>
template <typename T>
void sort(T* arr, int size, std::function<bool(T, T)> const & comparer)
{
// sort
}
int main()
{
int const size = 10;
int arr[size];
sort(arr, size, std::function{[](int num1, int num2) {
if (num1 > num2) {
return true;
} else {
return false;
}
}});
}
If you can change the signature of sort
, see walnut's answer .如果您可以更改
sort
的签名,请参阅walnut 的回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.