Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading a function defined in a namespace

Why is the following code illegal?

#include <iostream>
using namespace std;

namespace what {
void print(int count) {
    cout << count << endl;
}
}

void what::print(const string& str) {
    cout << str << endl;
}

int main() {
    what::print(1);
    what::print("aa");

    return 0;
}

The error I get when compiling with clang and -std=c++14 is

error: out-of-line definition of 'print' does not match any declaration in namespace 'what'

I know the fix to the problem but I am wondering why the compiler thinks that I am trying to define the function (print) instead of overload it.

like image 980
Curious Avatar asked Jun 05 '26 07:06

Curious


1 Answers

The reason it is not working for you is because the syntax

void what::print(const string& str)

is basically saying

inside the what namespace, define the print function here

If you want to define a function outside of its namespace, you must declare it in the namespace beforehand.

§13.1 of the standard states, "When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded."

Overloads of a function must be in the same scope of each other. It is just how the language works.

like image 108
Greg M Avatar answered Jun 06 '26 20:06

Greg M