1

First of all, this is completely for fun, and has little practical purpose, I guess.

What I'm attempting to do is. have 1 function, but I can call it with different function psuedonames.

so instead of doing:

calculate_result(int x, int y);

I could also do:

calculate_answer(int x, int y);

or I could even do:

calculation(int x, int y);

all of these would lead to this same function:

int calculate(int x, int y)
{
answer = x + y;
return answer;
}

so

int main()
{
int num1 = 5;
int num2 = 5;
int output =  (calculate_result(num1, num2) + calculate_answer(num1, num2) + calculation(num1, num2));
cout << output;
return 0;

}

I thought templates might be able to be used for this purpose? Is there any way of doing this?

jaym
  • 13
  • 3
  • 1
    Does this answer your question? [How do I assign an alias to a function name in C++?](https://stackoverflow.com/questions/3053561/how-do-i-assign-an-alias-to-a-function-name-in-c) This is mostly duplicated. – prehistoricpenguin Jul 03 '21 at 14:28

2 Answers2

1

The answer is: pointer to a function.

#include <iostream>
using namespace std;

int calculate(int x, int y)
{
  int answer = x + y;
  return answer;
}

int main() 
{
  // calculate_answer can now be used as a synonym to calculate
  auto calculate_answer = calculate;
  cout << calculate_answer(3, 4) << endl;
  return 0;
}
ivan_onys
  • 2,282
  • 17
  • 21
0

One of the possible solution is use of bind() defined under functional header file. Below is the code snippet.

#include <iostream>
#include <functional> // for bind()
using namespace std;

int calculate(int x, int y)
{
    return x + y;
}

int main()
{
    int num1 = 5;
    int num2 = 5;
    auto calculate_result = bind(calculate, num1, num2);
    auto calculate_answer = bind(calculate, num1, num2);
    auto calculation = bind(calculate, num1, num2);

    int output = (calculate_result() + calculate_answer() + calculation());
    cout << output;  //Prints 30 on console
    return 0;
}
Akash
  • 36
  • 5