std::for_each中的多态函子
Polymorphic functors in std::for_each
我正在尝试使用stl算法for_each,而不会在代码中大量使用模板。std::for_each想通过值实例化MyFunctor类,但由于它是抽象的,所以不能。我已经创建了一个函子适配器类,它传递一个指针,然后在适当的时候取消它。
我的问题:
STL或Boost是否已经有这样的适配器类?我不想重新发明轮子!
struct MyFunctor {
virtual ~MyFunctor() {}
virtual void operator()(int a) = 0;
}
namespace {
template<typename FunctorType, typename OperandType> struct
FunctorAdapter
{
FunctorAdapter(FunctorType* functor) : mFunctor(functor) {}
void operator()(OperandType& subject)
{
(*mFunctor)(subject);
}
FunctorType* mFunctor;
}; }
void applyToAll(MyFunctor &f) {
FunctorHelper<MyFunctor, int> tmp(&f);
std::for_each(myvector.begin(), myvector.end(), tmp); }
干杯,
Dave
您可以使用functional
中的功能适配器(及其垫片)。
#include <functional>
using namespace std;
for_each( vec.begin(), vec.end(), :mem_fun_ptr( &MyClass::f ) );
如果容器包含指向对象的指针,请使用mem_fun_ptr
,否则使用mem_fun
。除此之外,还有采用1个参数的成员函数的包装器:mem_fun1_ptr
和mem_fun1
。
@Evan:实际上,您可以为每个对象调用具有相同参数的成员函数。mem_fun1
包装器的第一个参数是this
指针,第二个参数是成员函数参数:
for_each( vec.begin(), vec.end(), bind2nd( mem_fun_ptr( &MyClass::f ), 1 ) );
有了更多的参数,您可以自己创建一个循环,或者创建一个具有表示参数的常量成员变量的自定义函子。
tr1::ref可能会在这里对您有所帮助——它是一个引用包装器,因此您可以通过引用传递普通对象以绑定或通过引用标准算法传递函数对象(甚至是抽象对象)。
// requires TR1 support from your compiler / standard library implementation
#include <functional>
void applyToAll(MyFunctor &f) {
std::for_each(
myvector.begin(),
myvector.end(),
std::tr1::ref(f)
);
}
但是,请注意,不支持decltype的编译器可能会拒绝传递对抽象类型的引用。。。因此,在获得C++0x支持之前,此代码可能不会编译。
为什么不使用BOOST_FOREACH?
http://www.boost.org/doc/libs/1_35_0/doc/html/foreach.html
听起来您可以从Boost::Function中受益。
如果我没记错的话,它也是一个只有头的库,所以很容易使用它。
忘记函子指针的所有包装,改为使用bind(functor_pointer,mem_fun1(&MyFunctor::operator());
作为函子?这样,您就不必担心以任何形式管理副本。
基于@xtofl的答案,由于数组包含int而不是"this"指针,我认为正确的咒语是
class MyClass
{
virtual void process(int number) = 0;
};
MyClass *instance = ...;
for_each( vec.begin(), vec.end(), binder1st(instance, mem_fun_ptr(&MyClass::process) );
与@xtofl的代码相比,唯一的区别是binder1st而不是binder2nd。binder2nd允许您将相同的数字传递给各种"this"指针。binder1st允许您将各种数字传递给一个"this"指针。
- 多态性和功能结合
- 具有默认模板参数的多态类的模板推导失败
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 多态二进制函数
- 访问存储在向量C++中的结构的多态成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 将 std::allocate_shared 与多态资源分配器一起使用
- 通过switch和static_cast访问多态对象的运行时类型
- C++boost序列化多态性问题
- 多态杆件变量 - 类设计
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- Doees the 'this' 指针参与虚函数的多态行为
- C++ 在堆栈中包含多态属性的类对象存储
- 基类和派生类的多态赋值运算符
- 转身多态对象
- 如何在基类指针向量的元素上应用重载的多态函数
- 具有智能指针的多态性
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- C++事件系统 - 多态事件和事件处理程序