Aayush Neupane
Aayush Neupane

Reputation: 1246

using directive and declaration in C++

does using directive has local scope??

i find in C++ primer book that " a using directive in a function treats the namespace names as being declared outside the function"

if it is like declared outside a function why doesn’t it make those names available to other functions in the file.

namespace Jill 
{ 
    double bucket(double n) { ... } 
    double fetch; 
    struct Hill { ... }; 
}
int main()
{
    using namespace Jill;
    return 0;
}
int foom()
{
    Hill top;              //error
    Jill::Hill crest;     //valid
}

if the statement "a using directive in a function treats the namespace names as being declared outside the function" is true than

`Hill top`

would have been valid?

Upvotes: 2

Views: 218

Answers (1)

songyuanyao
songyuanyao

Reputation: 172934

" a using directive in a function treats the namespace names as being declared outside the function"

The namespace names are treated as being declared outside the function, but it won't change the behavior of the implement of other functions, i.e. these names would be visible only in the function instroducing the using directive, they won't be visible in any other functions.

On the other hand, if there's a local function declaration in the function scope, it will be selected firstly other than the one introduced by the using directive.

e.g.

namespace Jill 
{ 
    double bucket(double n) { std::cout << "Jill::bucket\n"; return 0.0; } 
    double fetch; 
    struct Hill {}; 
}

int main()
{
    double bucket(double);
    using namespace Jill;
    bucket(0.0); // ::bucket but not Jill::bucket will be selected
    return 0;
}

double bucket(double n) { std::cout << "::bucket\n"; return 0.0; } 

LIVE

Upvotes: 3

Related Questions