Question

Example code

namespace many {
    namespace namespaces {
        class Bar {
        };

        template<typename T>
        void foo() {
        }
    }
}

Nothing fancy but to call foo with the template argument Bar it necessary (if no using directive is active) to write

many::namespaces::foo<many::namespaces::Bar>();

Which feels kind of silly when I know that all allowed types are in the namespace many::namespaces. So my question is if there is some way to implicitly lookup Bar in the correct namespace? That way I would be able to write

many::namespaces::foo<Bar>();

Which would be pretty handy especially in situation where I have multiple template arguments to pass. I know that ADL would allow

foo<many::namespaces::Bar>();

but that looks kind of weird to me.

So anyone knows if a macro-free solution exists for this?

Was it helpful?

Solution

Such a solution does not exist:

A template type parameter does neither establish its own scope, nor does it have any ADL-like lookup rules. Also, you cannot pass it any arbitrary token, but you need to pass it a type.

Therefore, whatever you pass it must be findable in the surrounding scope of your call. You can either qualify it, or pull it into one of the surrounding namespaces via using / typedef directives.

While ADL may seem a viable alternative (if you add a parameter) that means that you have something at hand whose type will cause the ADL to achieve the desired result. It should be noted that in that case you just wrote the type somewhere else in this scope and you can reuse it with decltype (and potentially a bit of type_traits magic).

P.S.: While macros can achieve the desired result (by establishing an additional scope and inserting a using namespace directive in that specific scope, or by prepending a full qualification) you explicitly did not want one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top