将函数模板传递给其他函数
Pass a function template to other function
假设我有一个函数对任意容器类型(C++11)执行某些操作:
template<class containerType>
void bar( containerType& vec ) {
for (auto i: vec) {
std::cout << i << ", ";
}
std::cout << 'n';
}
我可以从另一个类似的函数调用这个函数:
void foo() {
std::vector<int> vec = { 1, 2, 3 };
bar(vec);
}
现在假设我有不同的函数,就像bar一样,我想把其中一个函数传递给foo,那么foo会看起来像这样:
template<class funcType>
void foo( funcType func ) {
std::vector<int> vec = { 1, 2, 3 };
func(vec);
}
然而,像这样调用foo:
foo(bar);
不起作用(很清楚,因为bar不是一个函数,而是一个函数模板)。有什么好的解决方案吗?我必须如何定义foo才能使其工作?
编辑:这是一个最小的可编译示例,正如评论中所要求的。。。
#include <iostream>
#include <vector>
#include <list>
template<class containerType>
void bar( containerType& vec ) {
for (auto i: vec) {
std::cout << i << ", ";
}
std::cout << 'n';
}
template<typename funcType>
void foo(funcType func) {
std::vector<int> vals = { 1, 2, 3 };
func(vals);
}
int main() {
// foo( bar ); - does not work.
}
在线演示http://ideone.com/HEIAl
这允许您执行foo(bar)
。我们没有传入模板函数或模板类,而是传入一个具有模板成员函数的非模板类。
#include <iostream>
#include <vector>
#include <list>
struct {
template<class containerType>
void operator() ( containerType& vec ) {
for (auto i = vec.begin(); i!=vec.end(); ++i) {
std::cout << *i << ", ";
}
std::cout << 'n';
}
} bar;
template<typename funcType>
void foo(funcType func) {
std::vector<int> vals = { 1, 2, 3 };
func(vals);
}
int main() {
foo( bar );
}
如果您知道foo使用int向量,那么您可以传递bar< std::vector<int> >
函数。
一个合理的解决方案是,定义foo
的模块也为所使用的容器定义typedef。那么您甚至不需要bar
作为模板。
类似的东西?(没有完全清醒,可能会错过要点)
#include <iostream>
#include <vector>
#include <list>
struct Test{
template<class containerType>
static void apply( containerType& vec ) {
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << ", ";
}
std::cout << 'n';
}
};
template<class FuncStruct>
void foo() {
std::vector<int> vals;
vals.push_back(1);
FuncStruct::apply(vals);
}
int _tmain(int argc, _TCHAR* argv[])
{
foo<Test>();
return 0;
}
相关文章:
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- C++变量名(可以将 main 声明为变量,但对于其他函数名称则不然)
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 为什么 ADL 的运算符函数行为与其他函数不同?
- 将其他函数中的变量用于主函数C++
- 使用函数打开文件,然后让其他函数利用该文件?
- 如何创建一个函数来执行其中的其他函数
- 是否可以将多个结构作为一个数据包存储在一个函数中,然后传递给其他函数并在那里提取?
- 变量 z 无法从其他函数访问变量 x
- 将 libstdc++ 和其他函数组合到一个库中
- 休眠函数,但不阻止其他函数和代码
- 我的代码只会运行主函数,其他函数不会在C++中编译
- 传递多个参数的功能,该函数将类包含到其他函数
- 仅一个功能的链接错误.在同一类和CPP文件中具有相似签名的其他函数工作正常
- 如果从在其他函数中调用的函数引发异常会发生什么情况
- 为什么在其他函数中声明的函数不参与参数相关查找?
- C++ - 有没有办法只继承一次某些函数,而其他函数在多次继承中多次继承?
- 我应该删除来自其他函数或类方法的指针吗?
- Windows表单如何使用其他函数回调图表信息
- 关于函数调用,我的程序没有读取我的其他函数。为什么?