【发布时间】:2011-05-20 03:25:08
【问题描述】:
有人能解释一下为什么这段代码在codepad 上不起作用吗?
修改后的版本(带有虚函数)实际上可以工作 -
工作版 - http://codepad.org/5rRIg5zT
不工作的版本(下) - http://codepad.org/4PO2rBqS
我的意思是,这实际上是有效的 C++,还是键盘编译器错误?
更新:还有另一种工作方式可以做到这一点 - http://codepad.org/j6GAKXov 但它不是完全自动的。
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
typedef unsigned int uint;
typedef unsigned short word;
typedef unsigned char byte;
#ifdef __GNUC__
#define NOINLINE __attribute__((noinline))
#else
#define NOINLINE __declspec(noinline)
#endif
#include <setjmp.h>
enum{
STKPAD=1<<16,
STKSAV=1<<10
};
template <typename T>
struct coroutine {
volatile uint state;
volatile char* stkptrH;
volatile char* stkptrL;
jmp_buf PointA, PointB;
char stack[STKSAV];
coroutine() { state=0; }
NOINLINE // necessary for IntelC + my_setjmp.h
void yield( int value ) {
char curtmp; stkptrL=(&curtmp)-16; // -16 is necessary for MSC
if( setjmp(PointB)==0 ) {
state = value;
memcpy( stack, (char*)stkptrL, stkptrH-stkptrL );
longjmp(PointA,1);
}
}
NOINLINE // necessary for MSC, to avoid allocation of stktmp before setjmp()
void call_do_process() {
char stktmp[STKPAD]; stkptrH = stktmp;
((T*)this)->do_process();
}
uint call( void ) {
if( setjmp(PointA)==0 ) {
if( state ) {
memcpy( (char*)stkptrL, stack, stkptrH-stkptrL );
longjmp(PointB,1);
}
call_do_process();
}
return state;
}
};
struct index : coroutine<index> {
void do_process( void ) {
uint a=1;
while(1) {
yield( a );
a++;
}
}
} F1;
struct fibonacci : coroutine<fibonacci> {
void do_process( void ) {
uint a=0,b=1;
while(1) {
yield( b );
b = b + a;
a = b - a;
}
}
} F2;
int main( int argc, char** argv ) {
for( int i=0; i<20; i++ ) {
printf( "%i:%i ", F1.call(), F2.call() );
} printf( "\n" );
return 0;
}
【问题讨论】:
-
我收到您在此问题中发布的编译错误。你得到了什么?
-
它适用于 windows 上的 gcc 4.3+/intelc/VS,iphone 上的 gcc 4
-
您为什么不使用您的代码发布一个指向键盘的链接?
-
它们在这里和键盘上是不同的。键盘版有虚函数,效率低。
-
是的,这就是为什么我要求使用您问题中的代码链接到键盘,因此我们不必手动复制您的代码并将其粘贴到键盘中。无论如何,据我所知,codepad 的编译器似乎不喜欢不完整的类型作为模板参数。