如何在 C++ 中将模板化函数作为另一个函数的参数提供给默认值?
How to supply a templated function as a parameter for another function, with a default value, in C++?
如何将模板化函数作为另一个函数的参数,并使用默认值?
例如,如果我想提供一个带有模板化排序函数的函数,但将其默认设置为 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),所以你必须明确地编写函数 class 的代码(但它给了你更多的重载灵活性):
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 中执行的 best/simplest。
如何将模板化函数作为另一个函数的参数,并使用默认值?
例如,如果我想提供一个带有模板化排序函数的函数,但将其默认设置为 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),所以你必须明确地编写函数 class 的代码(但它给了你更多的重载灵活性):
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 中执行的 best/simplest。