如何在C++中提供模板化函数作为另一个函数的参数,默认值?

How to supply a templated function as a parameter for another function, with a default value, in C++?

本文关键字:函数 另一个 参数 默认值 C++      更新时间:2023-10-16

如何将一个模板化函数作为另一个函数的参数,并具有默认值?

例如,如果我想为函数提供模板化排序函数,但将其默认为 std::sort,那会是什么样子?

以下方法不起作用:

#include <algorithm> // std::sort
template <class iterator_type, class sort_comparison>
void temp(void (*sort_func)(iterator_type, iterator_type, sort_comparison) = std::sort)
{
return;
}

int main()
{
temp();
return 0;
}

根据 gcc 错误,它似乎仍然需要提供的参数。

另一种较少约束的解决方案是将std::sort或其他函数模板调用包装到 lambda 对象中:

template <class Container, class Sort>
void temp(Container& c, Sort sort) {
sort(c);
}
template <class Container>
void temp(Container& c) {
temp(c, [](auto& c) { std::sort(c.begin(), c.end()); });
}
int main() {
std::vector<int> v;
temp(v);
temp(v, [](auto& c) { std::stable_sort(c.begin(), c.end()); });
std::list<int> l;
temp(l, [](auto& c) { c.sort(); }); // std::sort is incompatible with std::list
}

在 C++03 中,lambda 表达式不可用(有有限的替代品,如boost::lambda但它具有完全相同的限制,即它需要指向函数的指针,不能调用函数模板,不像 C++11 lambda(,因此您必须显式编写该函数类(但它在重载方面为您提供了更大的灵活性(:

struct Sort {
template<class C>
void operator()(C& c) {
std::sort(c.begin(), c.end());
}
template<class T, class A>
void operator()(std::list<T, A>& c) {
c.sort();
}
};
// ...
temp(v, Sort());
temp(l, Sort());

尽管如此,这可能是 C++03 中最简单、最快速的编译和执行解决方案。它是冗长的和非本地的,但这是您在 C++03 中可以做的最好/最简单的事情。