如何在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(,因此您必须显式编写该函数类(但它在重载方面为您提供了更大的灵活性(:
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 中可以做的最好/最简单的事情。
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何在qt中从另一个类调用函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 将 N-arg 函数包装到另一个函数中
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- C++从另一个函数退出函数
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 在一个类中使用另一个类中的函数,而不在 c++ 中使用继承
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?