将功能模板传递给其他功能 [英] Pass a function template to other function
问题描述
假设我有一个函数可以对任意容器类型(C ++ 11)进行操作:
Suppose I have a function that does something on an arbitrary container type (C++11):
template<class containerType>
void bar( containerType& vec ) {
for (auto i: vec) {
std::cout << i << ", ";
}
std::cout << '\n';
}
我可以从另一个这样的函数调用这个函数:
I can call this function from another function like this:
void foo() {
std::vector<int> vec = { 1, 2, 3 };
bar(vec);
}
现在假设我像bar一样具有不同的功能,并且我想将其中一个功能传递给foo,那么foo看起来像这样:
Now suppose I have different functions just like bar, and I want to pass one of these functions to foo, then foo would look something like this:
template<class funcType>
void foo( funcType func ) {
std::vector<int> vec = { 1, 2, 3 };
func(vec);
}
但是,这样调用foo:
However, calling foo like this:
foo(bar);
不起作用(非常清楚,因为bar不是函数而是函数模板).有什么好的解决方案吗?我该如何定义foo才能使它正常工作?
does not work (pretty clear, since bar is not a function but a function template). Is there any nice solution to this? How must I define foo to make this work?
这是一个最小的可编译示例,根据注释的要求...
here is a minimal compileable example, as demanded in the comments...
#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.
}
推荐答案
是这样的吗? (尚未完全清醒,可能会遗漏要点)
Something like this? (not fully awake, might miss the point)
#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;
}
这篇关于将功能模板传递给其他功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!