|
From: | Scott Christley |
Subject: | data type polymorphism |
Date: | Fri, 20 Mar 2015 14:39:23 -0500 |
Hello, This is more a generic Objective-C question versus GNUstep but maybe some experts here have a suggestion. I have a bunch of code that looks l like this: if ([encode isEqual: [BioSwarmModel floatEncode]]) { // interpret as float matrix float (*grid)[height][width] = matrix; for (i = 0;i < height; ++i) for (j = 0;j < width; ++j) (*grid)[i][j] = 0.0; } else if ([encode isEqual: [BioSwarmModel doubleEncode]]) { // interpret as double matrix double (*grid)[height][width] = matrix; for (i = 0;i < height; ++i) for (j = 0;j < width; ++j) (*grid)[i][j] = 0.0; } where I have a generic pointer void *matrix to some data, that I need to interpret as a specific data type, generally either int, float or double. The part I don’t like is that the operation is essentially identical regardless of the data type, but I have to duplicate code in order to handle it. In this example, the code is just zero’ing out the data. This can be a pain for more complicated operations as I have to make sure I do the correct changes to each code piece. What I would like is just to write the code once and have the compiler or whatever handle the data type for me: for (i = 0;i < height; ++i) for (j = 0;j < width; ++j) (*grid)[i][j] = 0.0; So is there some new Objective-C feature that I’m unaware of which can do this for me? I know at the C language level, there essentially has to be separate code generated for each data type. I can do some trickery with C-preprocessor macros, or #include code snippets but I’ve avoided that at the moment. cheers Scott |
[Prev in Thread] | Current Thread | [Next in Thread] |