【发布时间】:2012-03-07 16:50:28
【问题描述】:
假设我有一个对任意容器类型 (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 才能使其工作?
编辑:根据 cmets 的要求,这是一个最小的可编译示例...
#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.
}
【问题讨论】:
-
你缺少最小的可编译示例
-
为什么要使用函数指针?我相信在这里使用仿函数会更好。
-
@AlexTheo 感谢您的评论。当然,使用函子解决方案很简单! Bob 发布了一个类似的解决方案作为答案。我会去的!
标签: c++ templates function-pointers