using directive vs using declaration swap in C++

前端 未结 3 1497
囚心锁ツ
囚心锁ツ 2020-12-24 08:08

Please refer to the code below:

#include 

namespace N
{

    template 
    class C
    {
    public:
        void SwapWit         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 08:44

    Note: I have removed your swap definition in namespace std. It is not relevant here. Even with out it the code will have the same issues.


    This is due to look up rule differences between using directive(using namespace std) and the using declaration(using std::swap)

    Microsoft says

    If a local variable has the same name as a namespace variable, the namespace variable is hidden. It is an error to have a namespace variable with the same name as a global variable.

    #include
    
    namespace T {
        void flunk(int) { std::cout << "T";}
    }
    
    namespace V {
        void flunk(int) { std::cout << "V";}
    }
    
    
    int main() {
        using T::flunk;   // makes T::flunk local
        // using V::flunk;  // makes V::flunk local. This will be an error
        using namespace V;  // V::flunk will be hidden
        flunk(1);
    }
    

    According to this, due to your

    template 
    void swap(C & c1, C & c2)
    

    std::swap will be hidden when you use

    using namespace std; 
    

    So the only swap available for template deduction is N::swap and it won't work for ints because it expects a template class as argument.

    but not when

    using std::swap;
    

    In this case it becomes equivalent to local definition. And can be used with out problem.

提交回复
热议问题