开发者

CGFloat-based math functions?

开发者 https://www.devze.com 2023-02-18 04:10 出处:网络
In both OS X and iOS, Apple is using the CGFloat typedef to automatically get a float on 32-bit systems and a double on 64-bit systems. But when using the normal Unix math functions you need to make t

In both OS X and iOS, Apple is using the CGFloat typedef to automatically get a float on 32-bit systems and a double on 64-bit systems. But when using the normal Unix math functions you need to make that decision on a case by case basis.

For example the floor() function is defined as:

double floor(double x);

and the floorf() function is defines as:

float floorf(float x);

I know all iOS devices are 32-bit today, but the reason to use CGFloat is to automatically get improved precision when the first 64-bit iOS devices are introduced (iPad 5?) and not having to change any code. But to make that possible we need CGFloat-based math functions:

CGFloat Floor(CGFloat x);

Are there any functions like that in iOS or any third-party libraries? Or how do other developers handle this? I suspect most are either using CGFloat together with the float-versions on iOS but then you would "need" to change every line with a math function if compiling for a 64-bit iOS device (and handle two different versions of of your code base).

Or you could just use float instead of CGFloat everywhere and not worrying about 64-bit iOS. B开发者_运维百科ut then you would get inconsistency with Apple's libraries and IMHO uglier code.

Or you could maybe use CGFloat together with the double-versions and just take the space and performance hit of letting the compiler convert between double and float all the time. And not caring about possible "Implicit conversion to 32 Bit Type" warnings.

Or maybe the best strategy, bet on no 64-bit version of iOS will ever arrive (or at least in a near enough future) and use CGFloat together with float-versions of the Unix math functions and not worrying about the future.

What strategy are you using?


Edit: So this question is no longer theoretical now that we have 64-bit iOS!

I think the easiest way to deal with this is to use tgmath.h, instead of math.h (math.h gets imported by Cocoa automatically, tgmath doesn't so you'll need to declare it somewhere).

There are a number of potential solutions discussed at the Cocoa mailing list thread: http://www.cocoabuilder.com/archive/cocoa/291802-math-functions-with-cgfloat.html

I would agree with the majority of people on that list that tgmath is probably the way to go. I believe it was originally intended to allow easy porting of Fortran code, but it also works in this scenario. TGMath will let you do:

double floor(double x);
float floor(float x);
long double floor(long double x);
0

精彩评论

暂无评论...
验证码 换一张
取 消