これは本当に遅いですが、これを行う方法を理解しようとしていて、この質問に遭遇しました。私が使用している環境では C++11 (別名 C++0x) または Boost を使用できませんが、どちらも素晴らしいものです。後世の。
UncleBens がほのめかしたように、STL の機能ヘッダーには、C++ 11 または Boost を使用していない場合に役立つ機能がいくつかあります:
http://www.cplusplus.com/reference/std/functional/
この問題は、2 番目のテンプレート関数を呼び出したくないということよりも、もう少し一般的なものです。たとえば、ファンクタの戻り値の型のベクトルを構築したい場合があります。この場合、2 番目のテンプレート関数の呼び出しは機能しない可能性があります。
関数のオーバーロード (関数ポインターとファンクターの両方を操作するため) と stl を使用することで、これを機能させることができます。変数を明示的に宣言した後、引数が 1 つのファンクター/関数の引数の結果を出力する例を次に示します。
#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/
しかし、それは私が必要としていたものにはうまくいきました。多分それは他の誰かのために働くでしょう。