我没有使用 C++11 或 Boost。我想使用函子并传递给 std::for_each 等算法,但我认为必须在函数之外定义函子太麻烦了。我想在使用它们之前在函数中本地定义它们。但是,以下不起作用。这是由于旧的 C++ 标准不允许将本地定义的类用作模板参数(在 C++11 中修复)。
int main()
{
std::vector<int> v(10);
class SetInc
{
public:
SetInc() : x(0) {}
virtual void operator () (int& a)
{
a = x++;
}
private:
int x;
} f;
std::for_each(v.begin(), v.end(), f);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n"));
}
但我已经开发了以下解决方法:
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>
template <typename ARGUEMENT, typename RESULT>
class FunctorBase
{
public:
typedef ARGUEMENT argument_type;
typedef RESULT result_type;
virtual result_type operator () (argument_type) = 0;
FunctorBase() {}
virtual ~FunctorBase() {}
};
template <typename ARGUEMENT, typename RESULT>
class FunctorWrapper
{
public:
typedef ARGUEMENT argument_type;
typedef RESULT result_type;
typedef FunctorBase<argument_type, result_type> Functor_T;
explicit FunctorWrapper(Functor_T *functor)
: functor(functor)
{}
result_type operator () (argument_type a)
{
return (*functor)(a);
}
private:
Functor_T *functor;
};
template <typename ARGUEMENT, typename RESULT>
FunctorWrapper<ARGUEMENT, RESULT> make_unary_functor(FunctorBase<ARGUEMENT, RESULT>& f)
{
return FunctorWrapper<ARGUEMENT, RESULT>(&f);
}
int main()
{
std::vector<int> v(10);
class SetInc : public FunctorBase<int&, void>
{
public:
SetInc() : x(0) {}
virtual result_type operator () (argument_type a)
{
a = x++;
}
private:
int x;
} f;
std::for_each(v.begin(), v.end(), make_unary_functor(f));
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n"));
}
这样好吗?