你的点子也没什么,但你不能传递一个类型,但一个值(具体来讲,函数指针>另外,通过一个模板策略提供功能 - 这是一个好主意,阅读现代。 C++设计由安德烈Alexandrescu的。
#include <iostream>
int f(int x) { return 2 * x; }
int g(int x) { return -3 * x; }
typedef int (*F)(int);
template<F f>
int do_work()
{
return f(7);
}
int main()
{
std::cout << do_work<f>() << '\n'
<< do_work<g>() << '\n';
}
OR
int calculate() { return 4; }
struct F { int do_something_with(int x) { return 2 * x; } };
struct G { int do_something_with(int x) { return -3 * x; } };
// or, make these functions static and use Operator::do_something_with() below...
template<typename Operation>
int do_work()
{
int v = calculate(7);
return Operation().do_something_with(v);
}
int main()
{
std::cout << do_work<F>() << '\n'
<< do_work<G>() << '\n';
}
+1:非常好的解决方案。不适用于支持我的问题的问题,但作为一般解决方案非常好! – 2010-10-25 19:45:12