views:

223

answers:

5

It's easy to create a new name for a type, a variable or a namespace. But how do I assign a new name to a function? For example, I want to use the name holler for printf. #define is obvious... any other way?

Solutions:

  1. #define holler printf
  2. void (*p)() = fn; //function pointer
  3. void (&r)() = fn; //function reference
  4. inline void g(){ f(); }
+6  A: 

int (*holler)(const char*, ...) = std::printf;

MSalters
+13  A: 
typedef int (*printf_alias)(const char*, ...);
printf_alias holler = std::printf;

Should do you fine.

jer
+8  A: 

You can create a function pointer or a function reference:

void fn()
{
}

//...

void (*p)() = fn;//function pointer
void (&r)() = fn;//function reference
Brian R. Bondy
This takes the cake. I didn't know about function references.
Vulcan Eager
@Vulcan: They are almost the same in that you can call both of them with the same syntax, but their addresses are a little diff. r doesn't take up its own memory space holding an address.
Brian R. Bondy
+1  A: 

Why do you need to do this? Unless you have a very good reason, I'd recommend not doing this. You should also check your company's coding standard, which (hopefully) has something like "Don't redefine the language" in it!

If you do this, you will make it harder for you or your colleagues to understand the code in the future; no one will thank you for that! If you absolutely must do it, make sure you include a comment explaining why you have to do it and apologising for doing it!

Mike P
+1  A: 

Use an inline wrapper. You get both APIs, but keep the single implementation.

John