[cpp] for_each中delete函数的适配问题
苏亚
su1981ya at 163.com
Wed Dec 6 20:50:53 CST 2006
lijie 写道:
> 2006/12/6, lijie <cpunion at gmail.com>:
>> 在 06-12-6,苏亚<su1981ya at 163.com> 写道:
>> > 这倒不用,c++会自动特化参数的,直接传Delete就可以了
>> >
>> > for_each(m_cpfsPosition.begin(),m_cpfsPosition.end(), Delete );
>>
>> 这样可以吗?Delete在特化以前是个不完整的类型,不能够直接使用,我在g++
>> 4.1.1上测试也是不行的,加上参数特化以后就可以了。
>>
>
> 或者是写成一个仿函数:
> class Test{
> public:
> ~Test(){cout << "Test::~Test()" << endl;}
> };
>
> struct Delete_{
> template <class T>
> void operator()(T* ptr){
> delete ptr;
> }
> };
>
> static Delete_ Delete;
>
> int main(){
> vector<Test*> vec;
> vec.push_back(new Test);
> for_each(vec.begin(), vec.end(), Delete);
> return 0;
> }
试了一下,果然不行:
#include <vector>
#include <algorithm>
using namespace std;
template <class T>
void Delete(T* ptr){ delete ptr;}
int main()
{
vector<int*> a;
a.push_back(new int(3));
for_each(a.begin(), a.end(), Delete);
}
我成功的例子是在类内用:
template<typename T1, typename T2, typename T3>
class CFuzzyRules
{
public:
。。。
void Uninit();
protected:
。。。
template<typename T>
void delptr(T* ptr){delete ptr;}
};
。。。
template<typename T1, typename T2, typename T3>
void CFuzzyRules<T1, T2, T3>::Uninit()
{
for_each(m_cpfsPosition.begin(),m_cpfsPosition.end(),delptr);//ptr_fun(
delete ) );
}
贴出来分析一下
More information about the Cpp
mailing list