【发布时间】:2019-04-10 14:01:30
【问题描述】:
我正在尝试将函数传递给模板,到目前为止我得到了这个:
template <typename T, typename U> void special_sort(std::vector<T>& container, std::vector<U>& ordering_container,
std::function<std::vector<std::pair<unsigned int, unsigned int>>(std::vector<U>&)>& sort_function) {
sort_function(ordering_container);
}
主要是这样声明的:
std::vector<std::pair<unsigned, unsigned>> sort_function(std::vector<int>&) {
std::vector<std::pair<unsigned int, unsigned int>> a;
return a;
}
int main() {
std::vector<std::string> test_container = {"a", "b", "c"};
std::vector<int> test_ordering_container = {4,7,2};
auto a = sort_function(test_ordering_container);
special_sort<std::string, int>(test_container, test_ordering_container, sort_function(test_ordering_container));
}
但我收到以下错误:
错误(活动)E0304 没有函数模板“special_sort”的实例与参数列表匹配 Objective_challenge C:\Users\mdp11\source\repos\Objective_challenge\Objective_challenge\main.cpp 21 个参数类型是:(
std::vector<std::string, @ 987654324@,std::vector<int, std::allocator<int>>,std::vector<std::pair<unsigned int, unsigned int>,std::allocator<std::pair<unsigned int, unsigned int>>>)
我做错了什么? 提前谢谢大家。
【问题讨论】:
-
你真正想要实现什么?顺便说一句
sort_function(test_ordering_container)这不是一个函数,但是你调用了这个函数,它返回一个向量,而一个向量不是函数;) -
我试图让那个模板函数接收 3 个参数,一个 T 的向量,一个 U 的向量,以及一个可以对第二个向量进行排序的函数,但我想在里面调用那个函数模板“special_sort”