簡體   English   中英

是否在名稱空間foo中聲明swap(),然后在同一名稱空間下使用swap()而不是foo :: swap()暗示foo :: swap()?

[英]Does declaring swap() in namespace foo and then using swap() instead of foo::swap() under the same namespace imply foo::swap()?

我的問題很簡單。 執行以下操作安全嗎?

不需要任何道德建議,例如“不要命名函數swap()!”。 或其他,請!

file1.hpp

//header guards here
#include <utility>  //includes std::swap and std::move

namespace foo 
{
    template<typename T>
    inline void swap(T& lhs, T& rhs)
    {
        T temp = std::move(lhs);
        lhs = std::move(rhs);
        rhs = std::move(temp);
    }
}

file2.cpp

#include "file1.hpp"

namespace foo
{
    template<typename T>
    void myfun(T a, T b) 
    { 
        a += b; 
        swap(a, b);  //does it imply foo::swap, because the function
                     //is declared in the foo namespace??
    } 

}

這完全取決於T的類型。

如果T的類型在具有自己的swap的不同命名空間中,則依賴於參數的查找將查找不同的swap() 否則,它將在當前名稱空間中查找。

#include <utility>  //includes std::swap and std::move
#include <iostream>

namespace foo
{
    template<typename T>
    inline void swap(T& lhs, T& rhs) {
        std::cout << "foo swap\n";
    }
}
namespace foo
{
    template<typename T>
    void myfun(T a, T b)
    {
        a += b;
        swap(a, b);  // Looks for swap using the type T.
                     // If not found uses the current namespace.
                     // If not found uses the enclosing namespace.
    }

}

namespace baz
{
    class X {
        public:
        X& operator+=(X const& rhs){return *this;}
    };
    inline void swap(X& lhs, X& rhs) {
        std::cout << "Bazz Swap\n";
    }
}

int main()
{
    baz::X  a,b;
    foo::myfun(a,b);  // finds ::baz::swap()
}

結果:

> a.out
Bazz Swap
>

它將調用foo::swap
您可以使用std::swap(a, b); 如果您想使用std實現

當然是。 首先在當前名稱空間中搜索不合格的名稱。

它將調用foo::swap() 有一個共同的成語是

using std::swap;
swap( x, y );

用通用代碼。 這可以啟用std::swap實現。但是,它也考慮了swap()函數,這些函數可以通過依賴於參數的查找(ADL)在其他命名空間中找到。 因此,如果有一個函數foo::swap並且xy的類型在namespace foo ,則該foo::swap將被調用,如果它比std::swap更好的話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM