败给new_handler了

mosal 2012-03-01 12:00:37
想定制个new_handler支持传参 代码如下:
#include <new>
#include <iostream>
#include <string>
using namespace std;
typedef void (*func)(string &);
void outOfmem(string &a)
{
cout << a << endl;
exit(-1);
}
template<typename FunT, typename Para>
struct pp
{
pp(FunT a, Para &b):pfunc(a), pstr(&b)
{
}
void operator() ()
{
pfunc(*pstr)
}
private:
FunT pfunc;
Para *pstr;

};
int main()
{
string a = "我们";
set_new_handler(pp<func, string>(outOfmem, a)());
char *p = new char[2147483647];

return 0;
}

编译器报错
operator.cpp(29) : error C2440: “<function-style-cast>”: 无法从“void”转换为
“std::new_handler”
void 类型的表达式不能转换为其他类型

std::new_handler 是函数指针类似如下定义
typedef void (*new_handler)()

请问应该怎么改,或者有什么其他办法?
...全文
93 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
无芒 2012-03-01
  • 打赏
  • 举报
回复

#include <new>
#include <iostream>
#include <string>
using namespace std;
typedef void (*func)(string &);

void outOfmem(string &a)
{
cout << a << endl;
exit(-1);
}

template<typename FunT, typename Para>
struct pp
{
pp(FunT a, Para &b):pfunc(a), pstr(&b)
{
}
new_handler operator() ()
{
pfunc(*pstr);
return new_handler();
}
private:
FunT pfunc;
Para *pstr;

};

int main()
{
string a = "我们";
set_new_handler(pp<func, string>(outOfmem, a)());
char *p = new char[2147483647];

return 0;
}

mosal 2012-03-01
  • 打赏
  • 举报
回复
有其他方法吗[Quote=引用 2 楼 pengzhixi 的回复:]

pp<func, string>(outOfmem, a)())
你这里是一个函数调用,得到的是该调用的返回值void也就是什么都没有
[/Quote]
mosal 2012-03-01
  • 打赏
  • 举报
回复
功能实现了,可是这样会死循环,还有高招吗?[Quote=引用 1 楼 wm_bunb 的回复:]

C/C++ code

#include <new>
#include <iostream>
#include <string>
using namespace std;
typedef void (*func)(string &);

void outOfmem(string &a)
{
cout << a << endl;
exit(-1);
}

temp……
[/Quote]
pengzhixi 2012-03-01
  • 打赏
  • 举报
回复
pp<func, string>(outOfmem, a)())
你这里是一个函数调用,得到的是该调用的返回值void也就是什么都没有

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧