Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving a function implementation more than one name in c++

Let say I have a basic 2D vector class something like

class vector2
{
  int x, y;
}

these two values could be used to represent a position as well as a width and height. does C++ provide a away for me to impliment a function such as vector2::getXpos() and then also define vector2::getWidth() and have it use the same implementation.

I know that I could just make both of these function inline, but the compiler might decide to not inline these functions. so if getWidth just called getXpos you would end up with two function calls.

A more relistic example of what I would want to use this for is getLength() and erm... getSpan() (thinking of like a screen here for when you say 40" tv)

I would assume that this would be a simple case of something like a special function definition... I did find this page but this sounds like it is a C feature... and a bit of a hack to get working.

EDIT

I am not asking about the mechanics of inline functions... I basicaly want to do something functionally like

class MyClass
{
  void ActaullyDoStuff();
  public:
  void foo(){ActaullyDoStuff();}
  void bar(){ActuallyDoStuff();}
}

but where I can just write something like

class MyBetterClass
{
  public:
  void foo(){ /* BLOCK OF CODE */ }
  void bar(){ /* DO WHAT EVER foo() DOES */ }
}

I want bar() to be another way of just doing foo() so that the same functional code can have different, more appropriate names depending on the situation.

like image 287
thecoshman Avatar asked Nov 14 '10 15:11

thecoshman


2 Answers

but the compiler might decide to not inline these functions

Then the compiler probably has a good reason to do so.

I think this is a non problem, just have the function with the alternative name call the "real" function, and the compiler will most likely inline it.

EDIT:

If that didn't convince you, it is possible to use __forceinline in visual studio. Here is the way to force inline in GCC.

EDIT2:

class MyBetterClass
{
  public:
  void foo(){ /* BLOCK OF CODE */ }
  __forceinline void bar(){ foo(); /* DO WHAT EVER foo() DOES */ }
}
like image 72
ronag Avatar answered Sep 22 '22 16:09

ronag


Using C++11 you could do:

//works for non-template non-overloaded functions:

const auto& new_fn_name = old_fn_name;

Other solutions: How do I assign an alias to a function name in C++?

like image 33
jave.web Avatar answered Sep 21 '22 16:09

jave.web