这真的很晚了,但我试图弄清楚如何做到这一点并遇到了这个问题。我正在使用的环境不能使用 C++11(又名 C++0x)或 Boost,尽管这两者都很棒,所以我想我会发布我是如何做到这一点的的后代。
正如 UncleBens 所暗示的,如果您不使用 C++11 或 Boost,STL 中的功能标头具有一些有用的功能:
http ://www.cplusplus.com/reference/std/functional/
这个问题比不想调用第二个模板函数更普遍。例如,一个人可能想要构建一个函子返回类型的向量,在这种情况下调用第二个模板函数可能不起作用。
通过使用一些函数重载(对函数指针和函子进行操作)和 stl's ,我们可以完成这项工作。这是一个示例,它在显式声明变量后打印出单参数仿函数/函数参数的结果:
#include <iostream>
#include <functional>
using namespace std;
// Simple function [pointer] that adds one to its argument
int addOne(int n)
{
return n + 1;
}
// Simple functor that multiplies its argument by two
class timesTwo
{
public:
int operator()(int n) const { return n * 2; }
};
// Simple higher-order function: takes a functor f and calls f on n, returning the result
// This is your template function in which you want to know the return type of f
template <typename Functor>
void printResultImpl(Functor f, typename Functor::argument_type n)
{
typename Functor::result_type r = f(n);
cout << r << endl;
}
// Wrapper function for function pointer
template <typename Arg, typename Result>
void printResult(Result (*f)(Arg), Arg n)
{
printResultImpl(ptr_fun(f), n);
}
// Wrapper function for functor (function object)
template <typename Functor, typename Arg>
void printResult(Functor f, Arg n)
{
printResultImpl(bind1st(mem_fun(&Functor::operator()), &f), n);
}
// Prints out 8 then 14
int main()
{
printResult(addOne, 7);
printResult(timesTwo(), 7);
}
这种方法有几个限制: 1. 你不能让你的函数返回函子的结果类型(因为包装函数不知道结果类型) 2. 它依赖于 stl 中的 unary_function 或 binary_function。正如 UncleBens 所展示的,可以扩展到其他类型 - 只需遵循以下声明的模式:
http ://www.cplusplus.com/reference/std/functional/
但它满足了我的需要;也许它会对其他人有用。