using directive vs using declaration swap in C++

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

Please refer to the code below:

#include 

namespace N
{

    template 
    class C
    {
    public:
        void SwapWit         


        
3条回答
  •  时光说笑
    2020-12-24 09:04

    The obvious reason is that a using declaration and a using directive have different effects. A using declaration introduces the name immediately into the current scope, so using std::swap introduces the name into the local scope; lookup stops here, and the only symbol you find is std::swap. Also, this takes place when the template is defined, so later declarations in namespace std aren't found. In the following line, the only swap that will be considered is the one defined in , plus those added by ADL (thus, the one in namespace N). (But is this true with VC++? The compiler doesn't implement name lookup correctly, so who knows.)

    A using directive specifies that the names will appear "as if" they were declared in the nearest namespace enclosing both the directive and the nominated namespace; in your case, global namespace. And it doesn't actually introduce the names; it simply affects name lookup. Which in the case of a dependent symbol (or always, in the case of VC++) takes place at the call site.

    As for why you have this particular error message: probably more an issue with VC++, since there's certainly no non-deduceable contexts in your code. But there's no reason to expect the two variants be have the same behavior, regardless of the compiler.

提交回复
热议问题