Reputation: 266
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
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);
}
Upvotes: 4