[cpp] for_each中delete函数的适配问题
Weapon Liu
pongba at gmail.com
Wed Dec 6 13:59:27 CST 2006
>
> 语句:
> vector<CFuzzyShapeRule<T1>*> m_cpfsPosition;
> 。。。。。。
> for_each(m_cpfsPosition.begin(),m_cpfsPosition.end(), delete ); //(1) 或者
> for_each(m_cpfsPosition.begin(),m_cpfsPosition.end(),ptr_fun( delete )
> ); // (2)
>
> 错误:
> no matching function for call to `ptr_fun(<type error>)'
>
> 这里delete不是一个函数,而是一个语句,所以没有办法适配。 那么请问,除了
> 重新写一个函数来调用delete,如
>
> void delptr( T1* ptr )
> {
> delete ptr;
> }
> 还有没有什么方法直接使用这一类c++关键字,或对其进行适配?除了delete,还
> 有很多如sizeof等?
No, you have to write a little helper function in one way or another.
FWIW, you may want to use a generic one in order to save some future effort:
struct Releaser
{
template<typename T>
void operator()(T* obj_ptr)
{
delete obj_ptr;
}
};
This way, you can always do the job like this:
std::for_each(li.begin(),li.end(),Releaser());
P.S. There're two alternatives, one of which is using boost::lambda( not
a very good one, though), and the other is to use boost::ptr_container.
More information about the Cpp
mailing list