Wherefore inline unnamed namespaces? - c++

A quick one for the gurus: C++11 allows unnamed namespaces to be declared inline. This seems redundant to me; things declared in an unnamed namespace are already used as if they were declared in the enclosing namespace.
So my question is this: what does it mean to say
inline namespace /*anonymous*/ {
// stuff
}
and how is it different from the traditional
namespace /*anonymous*/ {
// stuff
}
that we know and love from C++98? Can anyone give an example of different behaviour when inline is used?
EDIT: Just to clarify, since this question has been marked as a duplicate: I'm not asking about named inline namespaces in general. I understand the use-case there, and I think they're great. I'm specifically asking what it means to declare an unnamed namespace as inline. Since unnamed namespaces are necessarily always local to a TU, the symbol versioning rational doesn't seem to apply, so I'm curious about what adding inline actually does.
As an aside, the standard [7.3.1.1], regarding unnamed namespaces, says:
inline appears if and only if it appears in the unnamed-namespace-definition
but this seems like a tautology to my non-language lawyer eyes -- "it appears in the definition iff it appears in the definition"! For bonus points, can anyone explain what this bit of standardese is actually saying?
EDIT: Cubbi claimed the bonus point in the comments:
the standard is saying that unnamed-namespace-definition behaves as if it were replaced by X where inline appears in X iff it appears in the unnamed-namespace-definition

I don't know whether it's the done thing to answer your own question on SO, but after some playing around my curiosity has been satisfied, so I may as well share it.
The definition of an inline namespace includes not only the hoisting of names into the enclosing namespace (which happens anyway for unnamed namespaces), but also allows templates defined within an inline namespace to be specialised outside it. It turns out that this applies to unnamed namespaces too:
inline // comment this out to change behaviour
namespace {
template <typename T> struct A {};
}
template <> struct A<int> {};
Without the inline, g++ complains about trying to specialise a template from a different namespace (though Clang does not). With inline, it compiles just fine. With both compilers, anything defined within the specialisation is still marked as having internal linkage (according to nm), as if it were within the unnamed namespace, but I guess this is to be expected. I can't really think of any reason why this would be useful, but there we go.
An arguably more useful effect comes from the change regarding argument-dependent lookup for inline namespaces, which also affects unnamed inline namespaces. Consider the following case:
namespace NS {
// Pretend this is defined in some header file
template <typename T>
void func(const T&) {}
// Some type definition private to this TU
inline namespace {
struct A {};
}
} // end namespace NS
int main()
{
NS::A a;
func(a);
}
Without inline, ADL fails and we have to explicitly write NS::func(a). Of course, if we defined the unnamed namespace at the toplevel (as one normally would), then we wouldn't get ADL whether it was inline or not, but still...

Here is one use that I have found:
namespace widgets { inline namespace {
void foo();
} } // namespaces
void widgets::foo()
{
}
In this example, foo has internal linkage and we can define the function later on by using the namespace::function syntax to ensure that the function's signature is correct. If you were to not use the widgets namespace then the void foo() definition would define a totally different function. You also don't need to re-open the namespace saving you a level of indentation.
If there is another function called foo in the widgets namespace already then this will give you an ambiguity instead rather than a nasty ODR violation.

Related

Why do I have to qualify the namespace for a function passed a typedef of the functions templated parameter type?

In this example why do I need to qualify the function call B::F() with its namespace? As the typedef of QF should match the type Q as I thought it was an alias for it, not really a new type?
Is there an elegant way around this that doesn't require a using statement in every function body?
namespace A
{
template<class T> struct V {};
template<class T> struct Q {};
typedef Q<float> QF;
template<class T>
inline void F(V<T> v) {}
namespace B
{
template<class T>
inline void F(Q<T> q) {}
}
namespace C
{
void Test();
}
}
using namespace A;
using namespace A::B;
void A::C::Test()
{
QF q;
// using namespace A::B; // Uncomment will work
F(q); // Error, tries A::F() and can't find B::F()
B::F(q); // Ok it uses B::F() as intended
}
int main()
{
return 0;
}
I'll try to show in what ways clang interprets the draft differently than gcc and msvc. When you call F(q) inside the definition of void A::C::Test(), the compiler tries to look up the name F in the scopes in which that call is made, and will stop looking for larger scopes as soon as that name (name, not particular overload) is found. The body of void A::C::Test() is inside the namespace C which is inside A which is inside the global namespace. So when you write the using directive in the global scope, the relevant passage in the standard [basic.lookup.unqual]:
In all the cases listed in [basic.lookup.unqual], the scopes are searched for a declaration in the order listed in each of the
respective categories; name lookup ends as soon as a declaration is
found for the name. If no declaration is found, the program is
ill-formed.
The declarations from the namespace nominated by a using-directive become visible in a namespace enclosing the using-directive; see
[namespace.udir]. For the purpose of the unqualified name lookup rules
described in [basic.lookup.unqual], the declarations from the
namespace nominated by the using-directive are considered members of
that enclosing namespace.
by point 2 implies that the name F (coming from A::B::F) is visible as if it was declared in the global scope, but by point 1 name lookup will find a name F sooner, in namespace A and will not look further. So it only finds void F(V<T> v) and this declaration is not fit for the call.
The more interesting story is with the using directive put inside the body of the function. The difference in approach is whether the definition of void A::C::Test() (which is also a declaration) appears in the global namespace or in namespace A::C. If you take the view that this is the global namespace (as clang apparently does), then the namespace enclosing the using-directive written inside the function is the global namespace and we are back to the explanation above. But if you believe that it appears in namespace A::C, then you bring in (among others) the declaration of void F(Q<T>) into A::C and regular lookup finds it.
A bonus observation is why you would still be able to call F(V<double>{}) since now the declaration void F(Q<T>) is in a narrower scope - and the answer is argument-dependent lookup, the namespace where V<T> is declared is going to be looked at too.
That's a story to scare the learner, but if you want practical guidance, do not use the shortcut with namespaces, use
namespace A::C
{
void Test()
{
...
}
}
so that the namespace in which it is declared is not subject to debate and put using namespace A::B; either in namespace scope or in function scope.
(And I'll try to figure out what was the real intended scope of the void A::C::Test() declaration-definition with wiser people).

gcc template resolution and namespaces

Warning, C++ hating ahead...
I have seen here slightly different variations of this issue, here is my take
namespace space {
}
template <typename T> struct C
{
void foo() {
using namespace space;
bar(t);
}
T t;
};
class A {
};
namespace space {
void bar(const A& a){
}
}
int main()
{
C<A> c;
c.foo();
return 0;
}
if bar is not inside a namespace, everything compiles ok. Putting a namespace breaks compilation with gcc. What is more interesting - gcc finds the function, but just don't feel like using it:
ConsoleApplication1.cpp: In instantiation of 'void C<T>::foo() [with T = A]':
ConsoleApplication1.cpp:26:10: required from here
ConsoleApplication1.cpp:8:8: error: 'bar' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point
instantiation [-fpermissive]
bar(t);
^
ConsoleApplication1.cpp:18:6: note: 'void space::bar(const A&)' declared here, later in the translation unit
void bar(const A& a){
Is there any sane reason for this behaviour, except that the standard says so? And is there any switch I can make gcc accept this code, since it seems there is no technical issue, and I do not see why such code should not work from a pure language standpoint.
templates are not macros. Name lookup of symbols is done in two contexts: first, where you wrote the template, and second pass of only argument-dependent lookup (ADL, or Koeing Lookup) when you pass the template a type (when the template "factory" is instantiated into an actual class or function).
When the function is in the same namespace as A, it is found via ADL. When it is not, it will not be. So when you moved the bar function into space::bar, it was no longer ADL-found with an argument of type A.
This is intentional, to both prevent your template from meaning completely different things at different spots, and to allow non-member interface extensions to types in their own namespace only.
Either use a traits class, stick such helper functions in the same namespace as the type, or pass in functors.
A traits class is probably easiest. Create a class with a static function foo (if you want a default implementation: otherwise leave empty). Call it from your template. Specialize it for A. Now you can implement special behavior for your A type at that point -- it could even call your space::bar function if that function is in view.
Putting bar in the same namespace as A is another solution, and I find it scales better than traits classes. Many of my personal traits classes end up falling back on an ADL lookup, as that lets me inject the handling code right next to where I define A. (The use of traits classes lets me also have my trait handle things in std, where I am not allowed to inject functions for ADL purposes for types living in std (you can inject ADL functions into std, but only for your own types))
The functor solution is how std::map works -- while it falls back on std::less<T> which falls back on operator<, it takes a functor that lets you specify how the key type should be compared within this map.
Is there any sane reason for this behaviour, except that the standard says so?
Sane or not, C++ usually requires names to be declared before use. You don't declare bar before using it; specifically, using namespace space only imports names that have been declared at that point, and not bar.
(If you care about the reason, it's because C++ inherited its declaration rules from the languages of half a century ago, when computers were somewhat primitive. Rules like this allowed compilation in a single pass, so that the compiler didn't have to keep waiting for the operator to put the stack of punch cards back into the hopper. Or something like that; I'm not quite sure how computers worked back then.)
And is there any switch I can make gcc accept this code
As the error message says, -fpermissive. But your code won't be portable if you don't stick to the standard.
This error has nothing to do with namespaces or templates at all, but is the standard error of using a function before it has been declared. Just as you cannot do:
void caller() { callee(); }
void callee() {}
But must instead do:
void callee() {}
void caller() { callee(); }
Or:
void callee();
void caller() { callee(); }
void callee() {}
... the same applies for more complicated functions involving templates and namespaces. Note that if you reorder slightly, it works just fine:
class A {
};
namespace space {
void bar(const A& a){
}
}
template <typename T> struct C
{
void foo() {
using namespace space;
bar(t);
}
T t;
};
int main()
{
C<A> c;
c.foo();
return 0;
}

Is that correct to use 'using namespace' instead of nesting the entities into parentheses?

I've got an argument with my colleague.
We have a class that is a member of a namespace (which is a member of the other namespace but that is not important here I think). In the header file, we nest the class block into the namespace block like this:
namespace NS {
class A {
void method();
// ...
};
}
And here is the .cpp file and the subject of our argument. I wrote:
using namespace NS;
void A::method() {
// ...
}
The colleague told me that I use the 'using' directive improperly, and I should have used here the same NS { ... } as in the header. (He's modified the code and got some compiler errors that he only managed to get rid of by removing the using directive and surrounding the code with NS { ... }.)
My point is that 'using' just affects the name lookup so A is looked for in the NS namespace, so my approach is correct, and his compiler problems were caused by something else but not by that 'using' directive.
Who is right and why?
Added: guys, please don't answer like 'I did this (or that) way many times', that's not much useful. We need the theory here: why this or that approach is right or wrong.
Your colleague is correct, you should wrap cpp with namesapce which means you define your funcitons inside namesapce NS.
namespace NS
{
void A::method()
{
// ...
}
}
You may get conflict name lookup if you have multiple A available.
The dangerous thing happening here is that the using declaration takes a snapshot of whatever entities named A::method in namespace NS have been seen by the time the using declaration is encountered.
Have a read of Google cpp style guilde regarding namespace, also 101 c++ coding standards
Both of you are right in different ways. You are right in that the using directive will let the compiler resolve A in void A::method() to be NS::A, but he is also right in that in most cases you are better off opening the namespace.
The reason is that not everything that is declared in the namespace in the header will be looked up, and for those elements you will need to open the namespace (or provide the qualification manually), so it makes sense to provide a uniform approach.
A common example is the definition of operators that are applied to the type:
// header
namespace NS {
class A { ... };
std::ostream& operator<<(std::ostream&,A const&);
}
// implementation file (incorrect):
using namespace NS;
std::ostream& operator<<(std::ostream& o, A const & a) {
// do something
}
The problem here is that function definitions (when the function name is not a qualified name) are self-declaring. In the header the operator is declared as ::NS::operator<<, but in the implementation file it is defined as std::ostream& ::operator<<(std::ostream&, NS::A const&). The using directive will allow the resolution of the A identifier to be NS::A, but it won't make that function definition reside in the NS namespace.
This leads to a subtle problem, where any use of that operator will find ::NS::operator<< due to ADL, but that operator is not defined anywhere (although there is a similar operator in a different namespace)
Having said all that, there are some coding conventions (where I work now has such a guideline) that require namespaces for all types and that free function definitions should be performed outside of the namespace and always qualified to avoid self declarations. In the example above, the operator would be defined in the implementation file as:
std::ostream& ::NS::operator<<(std::ostream& o, A const& a) { ... }
But unless you really get used to always qualifying, this is prone to errors if you forget the qualification of the function.
namespace NS {
class A {
void method();
// ...
};
}
Always done it that way...
It turns out it's not only "coding-style matter". Using namespace ... leads to linking error when defining and initializing a variable declared extern in header file. Take a look at example in my question. Definition of constant within namespace in cpp file
You are correct. I've been bitten by this a number of times (that is, bitten by thinking that using declarations don't do this). There are three ways you could write this, and all will work:
namespace NS
{
void A::method()
{ }
}
Or:
NS::A::method() { }
Or:
using namespace NS;
A::method() { }
However, in terms of style, I would suggest either the first or the second - using declarations can get hairy when you have multiple classes with the same name and methods around.
It is considered good practice not to use 'using namespace' in code declarations or libraries but its OK to use them for the actual program's code.
Ie: dont use it for the Cpp definition but you can use it when your calling the function/class outside.
This is all just good coding practice and unless other people are using your code it matters more what you want.
The best is to put the cpp code into Namespace { ... } for readability

What are inline namespaces for?

C++11 allows inline namespaces, all members of which are also automatically in the enclosing namespace. I cannot think of any useful application of this -- can somebody please give a brief, succinct example of a situation where an inline namespace is needed and where it is the most idiomatic solution?
(Also, it is not clear to me what happens when a namespace is declared inline in one but not all declarations, which may live in different files. Isn't this begging for trouble?)
Inline namespaces are a library versioning feature akin to symbol versioning, but implemented purely at the C++11 level (ie. cross-platform) instead of being a feature of a specific binary executable format (ie. platform-specific).
It is a mechanism by which a library author can make a nested namespace look and act as if all its declarations were in the surrounding namespace (inline namespaces can be nested, so "more-nested" names percolate up all the way to the first non-inline namespace and look and act as if their declarations were in any of the namespaces in between, too).
As an example, consider the STL implementation of vector. If we had inline namespaces from the beginning of C++, then in C++98 the header <vector> might have looked like this:
namespace std {
#if __cplusplus < 1997L // pre-standard C++
inline
#endif
namespace pre_cxx_1997 {
template <class T> __vector_impl; // implementation class
template <class T> // e.g. w/o allocator argument
class vector : __vector_impl<T> { // private inheritance
// ...
};
}
#if __cplusplus >= 1997L // C++98/03 or later
// (ifdef'ed out b/c it probably uses new language
// features that a pre-C++98 compiler would choke on)
# if __cplusplus == 1997L // C++98/03
inline
# endif
namespace cxx_1997 {
// std::vector now has an allocator argument
template <class T, class Alloc=std::allocator<T> >
class vector : pre_cxx_1997::__vector_impl<T> { // the old impl is still good
// ...
};
// and vector<bool> is special:
template <class Alloc=std::allocator<bool> >
class vector<bool> {
// ...
};
};
#endif // C++98/03 or later
} // namespace std
Depending on the value of __cplusplus, either one or the other vector implementation is chosen. If your codebase was written in pre-C++98 times, and you find that the C++98 version of vector is causing trouble for you when you upgrade your compiler, "all" you have to do is to find the references to std::vector in your codebase and replace them by std::pre_cxx_1997::vector.
Come the next standard, and the STL vendor just repeats the procedure again, introducing a new namespace for std::vector with emplace_back support (which requires C++11) and inlining that one iff __cplusplus == 201103L.
OK, so why do I need a new language feature for this? I can already do the following to have the same effect, no?
namespace std {
namespace pre_cxx_1997 {
// ...
}
#if __cplusplus < 1997L // pre-standard C++
using namespace pre_cxx_1997;
#endif
#if __cplusplus >= 1997L // C++98/03 or later
// (ifdef'ed out b/c it probably uses new language
// features that a pre-C++98 compiler would choke on)
namespace cxx_1997 {
// ...
};
# if __cplusplus == 1997L // C++98/03
using namespace cxx_1997;
# endif
#endif // C++98/03 or later
} // namespace std
Depending on the value of __cplusplus, I get either one or the other of the implementations.
And you'd be almost correct.
Consider the following valid C++98 user code (it was permitted to fully specialize templates that live in namespace std in C++98 already):
// I don't trust my STL vendor to do this optimisation, so force these
// specializations myself:
namespace std {
template <>
class vector<MyType> : my_special_vector<MyType> {
// ...
};
template <>
class vector<MyOtherType> : my_special_vector<MyOtherType> {
// ...
};
// ...etc...
} // namespace std
This is perfectly valid code where the user supplies its own implementation of a vector for a set of type where she apparently knows a more efficient implementation than the one found in (her copy of) the STL.
But: When specializing a template, you need to do so in the namespace it was declared in. The Standard says that vector is declared in namespace std, so that's where the user rightfully expects to specialize the type.
This code works with a non-versioned namespace std, or with the C++11 inline namespace feature, but not with the versioning trick that used using namespace <nested>, because that exposes the implementation detail that the true namespace in which vector was defined was not std directly.
There are other holes by which you could detect the nested namespace (see comments below), but inline namespaces plug them all. And that's all there is to it. Immensely useful for the future, but AFAIK the Standard doesn't prescribe inline namespace names for its own standard library (I'd love to be proven wrong on this, though), so it can only be used for third-party libraries, not the standard itself (unless the compiler vendors agree on a naming scheme).
http://www.stroustrup.com/C++11FAQ.html#inline-namespace (a document written by and maintained by Bjarne Stroustrup, who you'd think should be aware of most motivations for most C++11 features.)
According to that, it is to allow versioning for backward-compatibility. You define multiple inner namespaces, and make the most recent one inline. Or anyway, the default one for people who don't care about versioning. I suppose the most recent one could be a future or cutting-edge version which is not yet default.
The example given is:
// file V99.h:
inline namespace V99 {
void f(int); // does something better than the V98 version
void f(double); // new feature
// ...
}
// file V98.h:
namespace V98 {
void f(int); // does something
// ...
}
// file Mine.h:
namespace Mine {
#include "V99.h"
#include "V98.h"
}
#include "Mine.h"
using namespace Mine;
// ...
V98::f(1); // old version
V99::f(1); // new version
f(1); // default version
I don't immediately see why you don't put using namespace V99; inside namespace Mine, but I don't have to entirely understand the use-case in order to take Bjarne's word for it on the committee's motivation.
In addition to all the other answers.
Inline namespace can be used to encode ABI information or Version of the functions in the symbols. It is due to this reason they are used to provide backward ABI compatibility. Inline namespaces let you inject information into the mangled name (ABI) without altering the API because they affect linker symbol name only.
Consider this example:
Suppose you write a function Foo that takes a reference to an object say bar and returns nothing.
Say in main.cpp
struct bar;
void Foo(bar& ref);
If you check your symbol name for this file after compiling it into an object.
$ nm main.o
T__ Z1fooRK6bar
The linker symbol name may vary but it will surely encode the name of function and argument types somewhere.
Now, it could be that bar is defined as:
struct bar{
int x;
#ifndef NDEBUG
int y;
#endif
};
Depending upon Build type, bar can refer to two different types/layouts with same linker symbols.
To prevent such behavior we wrap our struct bar into an inline namespace, where depending upon the Build type the linker symbol of bar will be different.
So, we could write:
#ifndef NDEBUG
inline namespace rel {
#else
inline namespace dbg {
#endif
struct bar{
int x;
#ifndef NDEBUG
int y;
#endif
};
}
Now if you look at the object file of each object you build one using release and other with debug flag. You will find that linker symbols include inline namespace name as well. In this case
$ nm rel.o
T__ ZROKfoo9relEbar
$ nm dbg.o
T__ ZROKfoo9dbgEbar
Linker Symbol names may be different.
Notice presence of rel and dbg in the symbol names.
Now, if you try to link debug with release mode or vise-versa you will get a linker error as contrary to runtime error.
So to sum up the main points, using namespace v99 and inline namespace were not the same, the former was a workaround to version libraries before a dedicated keyword (inline) was introduced in C++11 which fixed the problems of using using, whilst providing the same versioning functionality. Using using namespace used to cause problems with ADL (although ADL now appears to follow using directives), and out-of-line specialisation of a library class / function etc. by the user wouldn't work if done outside of the true namespace (whose name the user wouldn't and shouldn't know, i.e. the user would have to use B::abi_v2:: rather than just B:: for the specialisation to resolve).
//library code
namespace B { //library name the user knows
namespace A { //ABI version the user doesn't know about
template<class T> class myclass{int a;};
}
using namespace A; //pre inline-namespace versioning trick
}
// user code
namespace B { //user thinks the library uses this namespace
template<> class myclass<int> {};
}
This will show a static analysis warning first declaration of class template specialization of 'myclass' outside namespace 'A' is a C++11 extension [-Wc++11-extensions]. But if you make namespace A inline, then the compiler correctly resolves the specialisation. Although, with the C++11 extensions, the issue goes away.
Out-of-line definitions don't resolve when using using; they have to be declared in a nested/non-nested extension namespace block (which means the user needs to know the ABI version again, if for whatever reason they were permitted to provide their own implementation of a function).
#include <iostream>
namespace A {
namespace B{
int a;
int func(int a);
template<class T> class myclass{int a;};
class C;
extern int d;
}
using namespace B;
}
int A::d = 3; //No member named 'd' in namespace A
class A::C {int a;}; //no class named 'C' in namespace 'A'
template<> class A::myclass<int> {}; // works; specialisation is not an out-of-line definition of a declaration
int A::func(int a){return a;}; //out-of-line definition of 'func' does not match any declaration in namespace 'A'
namespace A { int func(int a){return a;};} //works
int main() {
A::a =1; // works; not an out-of-line definition
}
The issue goes away when making B inline.
The other functionality inline namespaces have is allowing the library writer to provide a transparent update to the library 1) without forcing the user to refactor code with the new namespace name and 2) preventing lack of verbosity and 3) providing abstraction of API-irrelevant details, whilst 4) giving the same beneficial linker diagnostics and behaviour that using a non-inline namespace would provide. Let's say you're using a library:
namespace library {
inline namespace abi_v1 {
class foo {
}
}
}
It allows the user to call library::foo without needing to know or include the ABI version in the documentation, which looks cleaner. Using library::abiverison129389123::foo would look dirty.
When an update is made to foo, i.e. adding a new member to the class, it will not affect existing programs at the API level because they wont already be using the member AND the change in the inline namespace name will not change anything at the API level because library::foo will still work.
namespace library {
inline namespace abi_v2 {
class foo {
//new member
}
}
}
However, for programs that link with it, because the inline namespace name is mangled into symbol names like a regular namespace, the change will not be transparent to the linker. Therefore, if the application is not recompiled but is linked with a new version of the library, it will present a symbol abi_v1 not being found error, rather than it actually linking and then causing a mysterious logic error at runtime due to ABI incompatibility. Adding a new member will cause ABI compatibility due to the change in type definition, even if it doesn't affect the program at compile time (API level).
In this scenario:
namespace library {
namespace abi_v1 {
class foo {
}
}
inline namespace abi_v2 {
class foo {
//new member
}
}
}
Like using 2 non-inline namespaces, it allows for a new version of the library to be linked without needing to recompile the application, because abi_v1 will be mangled in one of the global symbols and it will use the correct (old) type definition. Recompiling the application would however cause the references to resolve to library::abi_v2.
Using using namespace is less functional than using inline (in that out of line definitions don't resolve) but provides the same 4 advantages as above. But the real question is, why continue to use a workaround when there is now a dedicated keyword to do it. It's better practice, less verbose (have to change 1 line of code instead of 2) and makes the intention clear.
I actually discovered another use for inline namespaces.
With Qt, you get some extra, nice features using Q_ENUM_NS, which in turn requires that the enclosing namespace has a meta-object, which is declared with Q_NAMESPACE. However, in order for Q_ENUM_NS to work, there has to be a corresponding Q_NAMESPACE in the same file⁽¹⁾. And there can only be one, or you get duplicate definition errors. This, effectively, means that all of your enumerations have to be in the same header. Yuck.
Or... you can use inline namespaces. Hiding enumerations in an inline namespace causes the meta-objects to have different mangled names, while looking to users like the additional namespace doesn't exist⁽²⁾.
So, they're useful for splitting stuff into multiple sub-namespaces that all look like one namespace, if you need to do that for some reason. Of course, this is similar to writing using namespace inner in the outer namespace, but without the DRY violation of writing the name of the inner namespace twice.
It's actually worse than that; it has to be in the same set of braces.
Unless you try to access the meta-object without fully qualifying it, but the meta-object is hardly ever used directly.
Inline namespaces can also be used to provide fine(r)-grained access to features/names within namespaces.
This is used in std::literals. The literals namespaces in std are all inline namespaces, so that:
if you use using namespace std; somewhere, you also get access to all user defined literals in the std.
but if you just need a set of udl in you local code, you can also do using namespace std::literals::string_literals; and you will just get the udl symbols defined in that namespace.
This seems a useful technique for symbols that you would want to access unqualified (udl, operators, etc.) where you can just bundle them up in an inline namespace so that you can do a specific using on just that (sub-) namespace instead of the namespace of the whole library.

SFINAE to test a free function from another namespace

I was trying to come up with a hack to test if std::isnan is defined without special casing compilers in the preprocessor, and came up with the following, which I was expecting to work fine.
#include <cmath>
#include <type_traits>
namespace detail {
using namespace std;
struct dummy {};
void isnan(dummy);
//bool isnan(float); // Just adding this declaration makes it work!
template <typename T>
struct is_isnan_available {
template <typename T1>
static decltype(isnan(T1())) test(int);
template <typename>
static void test(...);
enum { value = !std::is_void<decltype(test<T>(0))>::value };
};
}
int main() {
return detail::is_isnan_available<float>::value;
}
Turns out it doesn't detect it. I know for certain std::isnan is defined on ideone, because I tested that manually.
And when I uncomment the marked line above, it works.
What am I missing here? What explains this behaviour?
The thing is, that the using directive doesn't add members to the current namespace, so the std:: members could still be hidden by declarations in this namespace.
using std::isnan would instead behaves as if the members of the imported namespace were added to the namespace enclosing both the use-location and the imported namespace. The using declaration is a normal declaration in the namespace, so can take part in overload resolution with the declarations that follow.
However, as pointed out in the comments, that would produce an error if the function does not exist. To work around that you need to put it out of your detail:: namespace then. That should work, because the imported definition would be at the same level as the dummy overload. You can take the overload to the global namespace, or you can make an auxiliary namespace (in the global namespace) and import both.
I solved this problem for the set of POSIX thread-safe APIs which supersede non-thread-safe standard functions: C++11 alternative to localtime_r . This code detects whether an API is defined in the global namespace, and if it does not exist, selects a custom workaround.