How to resolve a name collision between a C++ namespace and a global function?

前端 未结 3 1726
情书的邮戳
情书的邮戳 2021-01-04 18:58

if I define a namespace log somewhere and make it accessible in the global scope, this will clash with double log(double) from the standard c

3条回答
  •  旧时难觅i
    2021-01-04 19:20

    cmath uses ::log for some reason to get it from the global scope and can't decide between the function and your namespace.

    Namespaces keep code contained to prevent confusion and pollution of function signatures.

    Here's a complete and documented demo of proper namespace usage:

    #include 
    #include   // Uses ::log, which would be the log() here if it were not in a namespace, see https://stackoverflow.com/questions/11892976/why-is-my-log-in-the-std-namespace
    
    // Silently overrides std::log
    //double log(double d) { return 420; }
    
    namespace uniquename {
        using namespace std;  // So we don't have to waste space on std:: when not needed.
    
        double log(double d) {
            return 42;
        }
    
        int main() {
            cout << "Our log: " << log(4.2) << endl;
            cout << "Standard log: " << std::log(4.2);
            return 0;
        }
    }
    
    // Global wrapper for our contained code.
    int main() {
        return uniquename::main();
    }
    

    Output:

    Our log: 42
    Standard log: 1.43508
    

提交回复
热议问题