Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the safest way to define short function name aliases in C++?

Suppose I have a class Utility in a file utility.h:

class Utility {
public:
    static double longDescriptiveName(double x) { return x + 42; }
};

And then I find that I use the function longDescriptiveName(...) a LOT. So like an irresponsible C++ programmer that I am when I've had too much coffee, I create a new file utilitymacros.h and add the following there:

#define ldn Utility::longDescriptiveName

Now I include "utilitymacros.h" in any *.cpp where I use ldn(...) and my heart is filled with joy over how much more convinient it is to type 3 letters vs 28.

Question: Is there a safer (more proper) way of doing this than with #define?

I've noticed that I have to include "utilitymacros.h" after including boost headers, which I obviously don't like because it's a sign of clashes (though the Boost errors I get are not very clear as to what the clash is).

Clarification 1: On Code Readability

In case you might say that this negatively affects code readability, I assure you it does not, because it's a small set of functions that are used A LOT. An example that is widely know is stoi for stringToInteger. Another is pdf for probabilityDensityFunction, etc. So if I want to do the following, stoi is more readable in my opinion:

int x = stoi(a) + stoi(b) + stoi(c) + stoi(d);

Than:

int x = Utility::stringToInteger(a) + Utility::stringToInteger(b)
        + Utility::stringToInteger(c) + Utility::stringToInteger(d);

Or:

int x = Utility::stringToInteger(a);
x += Utility::stringToInteger(b);
x += Utility::stringToInteger(c);
x += Utility::stringToInteger(d);

Clarification 2: Editor Macro

I use Emacs as my IDE of choice and a Kinesis keyboard so you KNOW I use a ton of keyboard macros, custom keyboard shortcuts, as well as actually modifying what I see in the editor vs what's actually stored in the h/cpp file. But still, I feel like the simplicity and visual readability (as argued above) of using a function abbreviation in a few select cases really is the result I'm looking for (this is certainly subject to a degree).

like image 607
Alan Turing Avatar asked Dec 30 '12 16:12

Alan Turing


2 Answers

Instead of macro, you could write inline function that forwards the call to the actual function:

inline double ldn(double x)
{
   return Utility::longDescriptiveName(x);
}

That is certainly safer than macro.

like image 69
Nawaz Avatar answered Oct 04 '22 02:10

Nawaz


You could use a function reference:

double (&ldn)(double) = Utility::longDescriptiveName;
like image 40
David G Avatar answered Oct 04 '22 00:10

David G