c++ why compiler cant find function overload when namespace is used?

42 Views Asked by At

I have below four files,

//struct.h
#pragma once
namespace coffee {
    class MD2 {};
    class Recorder{};
    class Book{};
}


//setup.h
#pragma once
#include "struct.h"
using namespace coffee;
void wire(MD2 md2, Book book){}

//strategy.h
#pragma once
#include "struct.h"
#include "setup.h"
namespace strategy {
    using namespace coffee;
    int wire(MD2 md2, Recorder recorder) {}
    int setup2(MD2 md2, Recorder recorder, Book book) {
        wire(md2, recorder);
        wire(md2, book); //<--compiler cant find this
    }
}

//main.cpp
#include <iostream>
#include "strategy.h"
int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

My problem is before using namespace coffee, the program compiles fine, but after adding namespace coffee, the compiler cant find wire(md2, book). May I know why?

1

There are 1 best solutions below

0
André Lehto On

As Joel pointed out in the comment to your post, you should not be using namespace in C++ headers.

To save any developer that might be working with you or with your code some headaches, I would also refrain from using using namespace altogether, as it will reduce readability of the code for any larger codebase.

Even for your small code example, I had to look twice to see that Recorder was part of coffee. Simple writing out coffee::Recorder etc., makes for more readable code and avoids annoying mistakes down the road.