jvn91173
jvn91173

Reputation: 266

Why can't I call any other overloads of the same function while inside a particular function overload in C++?

It's best to illustrate this question with a simple program.

#include <iostream>
#include <utility>

void printPoint(std::pair <int, int> point) {
    printPoint(point.first, point.second);
}

void printPoint(int x, int y) {
    std::cout << x << ' ' << y << std::endl;
}

int main(void) {
    std::pair <int, int> point(2, 3);
    printPoint(point);
    return 0;
}

I would like for the two printPoint functions to accomplish the same thing by taking advantage of overloads. However, while inside the scope of a particular overload of the printPoint function (in this case, the single-argument one), the compiler only lets me use that particular overload, so the code does not compile.

Why is this? Further, is there any way to mitigate this problem so that I don't have to re-write the same function body twice?

Upvotes: 3

Views: 86

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

Declaration order matters here.

Move the 2nd overload (printPoint(int, int)) before the 1st one (printPoint(std::pair <int, int>); otherwise it's invisible inside the 1st overload. i.e.

void printPoint(int x, int y) {
    std::cout << x << ' ' << y << std::endl;
}

void printPoint(std::pair <int, int> point) {
    printPoint(point.first, point.second);
}

LIVE

Upvotes: 4

Related Questions