views:

75

answers:

2

I came across a compile.. oddity? recently that led me to believe that a template, when created, is created in the same namespaces (or, at least, using the same namespaces) as where is was declared. That is;

template<class T>
class bar
{
public:
    static int stuff(){return T::stuff();}
};

namespace ONE
{
    struct foo
    {
        static int stuff(){return 1;}
    };
}

namespace TWO
{
    struct foo
    {
        static int stuff(){return 2;}
    };
}


using namespace TWO;

int main() 
{

    return bar<foo>::stuff();
}

will return 1 when using namespace ONE and 2 when using namespace TWO.

Why? And are there other "odd" or "unexpected" interactions between namespaces and templates?

Edit: This was confusing at the time because the same templates were being used across multiple files, each using a different namespace.

+6  A: 

That's not unexpected. You didn't qualify which foo you wanted, so your using declaration told the compiler where to find it.

The worst template gotcha I've seen in production code had to do with non-dependent name lookup. It's pretty complicated, so it's probably best to just point you at the C++ FAQ Lite (sections 35.18-20).

Kristo
+5  A: 

I'm not sure what's surprising here. When you say using namespace ONE you bring ONE::foo to scope, now recognized as foo. In the above code the template gets TWO::foo as its parameter. It has nothing to do with the template, everything that's going on is going on in main() when you call bar<T>::stuff().

wilhelmtell