2013-05-22 17 views
0

關於宏超載已經有很多問題/答案。但是,我找不到一種方法將其應用於我的特定問題。用於N-D數組賦值的C宏超載

我想方便賦值給我在C. 3D圖像現在,我做如下:

#define IMGET(im,y,x,c) im.data[(y)+im.height*((x)+im.width*(c))] 
#define IMSET(im,y,x,c,v) IMGET(im,y,x,c)=v 

它運作良好。

但是,我想使用它也當我有黑色&白色圖像,這只是二維。 東西,像這樣:

#define IMGET(im,y,x,c) im.data[(y)+im.height*((x)+im.width*(c))] //3D case 
#define IMSET(im,y,x,c,v) IMGET(im,y,x,c)=v //3D case 
#define IMGET(im,y,x) im.data[(y)+im.height*(x)] //2D case 
#define IMSET(im,y,x,v) IMGET(im,y,x)=v //2D case 

這可能嗎?

+0

那你試試?你是指[this](http://stackoverflow.com/q/9183993/153285)?我沒有看到有關此主題的「許多」項目。 – Potatoswatter

+0

這裏有一些我已經找到的鏈接http://stackoverflow.com/questions/11761703/overloading-macro-on-number-of-arguments http://stackoverflow.com/questions/679979/how-to-make- a-variadic-macro-variable-of-arguments http://stackoverflow.com/questions/5283197/c-macro-with-variable-number-of-arguments – Oli

+2

我已經[posted](http:// stackoverflow.com/q/16683146/153285)詳細的一般說明。希望能幫助到你。 – Potatoswatter

回答

0

@Potatoswatter的評論給出了一個非常好的和一般的解決方案。但是對於我這個簡單的問題來說這可能是一種矯枉過正。

看着它之後,我發現了以下解決方案:

#define IMGET(im,y,x,...) im.data[(y)+im.height*((x)+im.width*(__VA_ARGS__+0))] 

然後,我可以用這個宏對所有的下列情況:

float val = IMGET(im,y,x,c); 

或:

float val = IMGET(im,y,x,c); 

如果我想assingn,我這樣做:

IMGET(im,y,x,c)=val; 

IMGET(im,y,x)=val;