Template / Namespace Interactions - c++

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.

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).

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().

Related

MISRA C++ Rule 14-5-1: Name of generic function template declared in namespace associated with type

Is Warning 1573 ("Name of generic function template declared in namespace associated with type") really relevant when the namespace is an
anonymous namespace? Most of the helper functions I have for tests go in unnamed namespace and it breaks the above rule.
Example:
namespace
{
template <typename T>
T template_func(T arg)
{
return arg;
}
class foo {};
}
int main()
{
return template_func(0);
}
How do I get around in the above, to satisfy the rule?
As state in their example, you might use extra namespace, something like:
namespace
{
template< class T >
T template_func(T arg) { return arg; }
namespace X
{
class foo{};
}
using X::foo;
}
int main()
{
return template_func(0);
}
I'd guess that it isn't aimed at polluting global namespace but to avoid class picking up weird matches from generic templates belonging to the same namespace.
It goes along the cpp core guideline T.47: Avoid highly visible unconstrained templates with common names
Specifically:
Reason :
An unconstrained template argument is a perfect match for anything so such a template can be preferred over more specific types that require minor conversions. This is particularly annoying/dangerous when ADL is used. Common names make this problem more likely.
Note:
If an unconstrained template is defined in the same namespace as a type, that unconstrained template can be found by ADL (as happened in the example). That is, it is highly visible.
As for how to bypass it, Jarod42 was 1st with an example in his answer.

Can two "using" collide?

So I have to use some members of Boost library and some from the std namespace. Right now, I have using boost::asio::ip::tcp; declared and am calling appropriate members with std:: and for example tcp::iostream server(). Is there any reason why I shouldn't add another using, namely using namespace std; and then call all the std things without std:: prefix? Can these two somehow collide or cause malfunction?
Provided that it is usually considered a bad practice to have using directives that import names from the std namespace (especially when at namespace scope and/or in a header file), because it easily leads to name clashes, consider the following program:
namespace A { void foo() { } }
namespace B { void foo() { } }
int main()
{
using namespace A;
using namespace B;
foo();
}
How should the compiler resolve the call to foo()? Well, it won't. It is ambiguous, because both A::foo() and B:foo() can now be referred to as the unqualified foo().
If there are entities with the same name in the std namespace and in the global namespace (or in any other namespace for which you have a using directive), ambiguities due to name clashes are likely to arise.
In your specific case, a using directive such as:
using namespace std;
Will be unlikely to clash with the name tcp introduced by your using declaration (notice, that a using declaration imports just one specific name and is, therefore, preferable).
Yet, it is still considered to be poor programming style and you should not do it, regardless of whether you have some other using directive or using declaration already in place.
Yes, they can. The compiler can't resolve the correct namespace in that case. The solution is to use prefixes (for example std::).
You can also put the using namespace keywords inside a function or other block, so the namespace won't be used outside it:
void foo()
{
using namespace ns;
} // ns won't be used after this
Furthermore, namespace usage can be limited to a header:
namespace ns
{
#include "ns.h"
}
However, limiting the namespace to a header is not recommended because it causes problems in many cases.
The other answers do a good job of explaining how ambiguities can be resolved when you have two or more using namespace directives, but it's worth pointing out that the situation is different if you have using declarations that pull in two or more specific names from within namespaces, like this:
namespace A { void foo() { } }
namespace B { void foo() { } }
int main()
{
using A::foo;
using B::foo;
return 0;
}
The above is always a compile error, even though neither foo is ever used. This is because using declarations, as the name suggests, actually declare a name in their enclosing scope to be an alias to a name in some other namespace. This is in contrast to a using namespace directive, which merely makes names available in their enclosing scope without actually declaring any new names.
If you really want to, it's possible to resolve the above code like this:
using fooa = A::foo;
using foob = B::foo;
But using declarations should usually be avoided anyway, because they have some other semantic surprises which can bite you in unexpected, subtle, and sometimes undetectable ways. The exception is using a base class member within a derived class, which is usually OK, though not often necessary.

C++ Should I fully qualified my variable type?

I am trying to write lines of code fitting under 80 columns maximum. Thus, I wonder if fully qualifying my variable type is really mandatory ? Assuming the following implementation:
//Baz.h
namespace loggingapi {
namespace attributes {
class Baz {};
}} // namespaces
// Bar.h
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
int f(Baz* b);
};
} // namespaces
To declare my function parameter type, there are multiple ways ?
a) int f(Baz* b);
b) OR int f(attributes::Baz* b);
c) OR int f(loggingapi::attributes::Baz* b);
d) OR int f(::loggingapi::attributes::Baz* b);
In the list above, which definition(s) is/are clearer/ambiguous for the compilers ?
NOTE: You must assume the namespace/parameter/class/function names CANNOT be shortened in the following implementation.
Variant e ?
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
typedef attributes::Baz Baz;
// C++ 11 alternative
// using Baz = attributes::Baz;
int f(Baz* b);
}
} // namespaces
Do not forget what aliasing can do for you...
I would go with the b) variant. My reasons are as follows:
We assume that the developer knows in what namespace he is now. So when looking at the class Biz, the developer should know that this class is in the loggingapi namespace, therefore, there's no need to explicitly state it.
The a) variant, on the other hand, isn't clear enough, because we should indicate that Baz and Biz are actually in different namespaces. Also, it is not going compile, because the compiler will look for Baz in the loggingapi namespace, and it isn't there.
You should choose (b). It's more flexible. If you decide to move or (gasp) cut and paste f and it's related types to a new namespace or project then using (b) ensures that the structure of the declarations remains internally consistent.
You can choose to add, remove or rename outer wrapping namespaces without affecting the enclosed code.
In h-file it is better to use fully qualified names, to prevent possible ambiguity in a client code. In .cpp file you can use short notation, if you prefer this, as long as there is no name clash.
If a compiler has some ambiguity it will definitely report an error.
I believe the question should be with respect to the human reader, which is quite subjective.
The naming convention depends on
Pre-decided coding style
Where you are declaring the function f()
There is no clear choice over another. I would prefer that, if both entities are belonging to same namespace then I will omit at least that part from the name:
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
int f(attribute::Baz* b);
}; // ^^^^^^^^^^^^^
}

What is namespace used for, in C++?

What is namespace used for, in C++?
using namespace std;
Namespace is used to prevent name conflicts.
For example:
namespace foo {
class bar {
//define it
};
}
namespace baz {
class bar {
// define it
};
}
You now have two classes name bar, that are completely different and separate thanks to the namespacing.
The "using namespace" you show is so that you don't have to specify the namespace to use classes within that namespace. ie std::string becomes string.
It's used for preventing name confilct, so you may have two classes with the same name in different namespaces.
Also it's used for categorizing your classes, if you have seen the .net framework, you will see that namespaces are used for categorizing the classes. For example, you may define a namespace for the employee classes, and a namespace for the tasks classes, and both namespaces are within a namespace for the company classes, since a namespace may contain sub namespaces.
The same namespace may exist in different files, so using it may be useful because it will make you able to directly use all the classes in the namespaces in every #included file.
That's what I remember for now.
One could ask, simple pair of curly braces {} are sufficient to resolve name conflict. Still why have a NameSpace. A quick answer as Tamer mentioned above is that with NameSpace we get the ability to open the same scope in another file.
Namespace usually is used to prevent naming conflicts.
So, One place where namespace comes into picture is
class ABC{
// Does something for me.
};
class ABC{
// Does something for you..
};
int main() {
ABC myABC;
return 0;
}
This will give a compilation error as the system will not know which class is to be considered. Here the concept of namespace comes into picture.
namespace My{
class ABC{
// Does something for me.
};
}
namespace Your{
class ABC{
// Does something for you..
};
}
using My::ABC
// We explicitly mention that My ABC is to be used.
int main() {
ABC myABC;
return 0;
}
Code will be much organized with the usage of namespaces.

Preferred namespace syntax for source files

Assuming a class called Bar in a namespace called foo, which syntax do you prefer for your source (.cpp/.cc) file?
namespace foo {
...
void Bar::SomeMethod()
{
...
}
} // foo
or
void foo::Bar::SomeMethod()
{
...
}
I use namespaces heavily and prefer the first syntax, but when adding code using the Visual Studio Class Wizard (WM_COMMAND handlers, etc.) the auto-generated code uses the second. Are there any advantages of one syntax over the other?
I would decline the first (edit : question changed, the first is what i prefer too now). Since it is not clear where Bar refers to from only looking at the function definition. Also, with your first method, slippy errors could show up:
namespace bar {
struct foo { void f(); };
}
namespace baz {
struct foo { void f(); };
}
using namespace bar;
using namespace baz;
void foo::f() { // which foo??
}
Because it looks in the current scope (there it is the global scope), it finds two foo's, and tells you the reference to it is ambiguous.
Personally i would do it like this:
namespace foo {
void Bar::SomeMethod() {
// something in here
}
}
It's also not clear from only looking at the definition of SomeMethod to which namespace it belongs, but you have a namespace scope around it and you can easily look it up. Additionally, it is clear now that Bar refers to namespace foo.
The second way you show would be too much typing for me actually. In addition, the second way can cause confusion among new readers of your code: Is foo the class, and Bar a nested class of it? Or is foo a namespace and Bar the class?
I prefer an option not listed:
namespace foo {
void Bar::SomeMethod()
{
...
}
} // foo namespace
Unlike option one, this makes it obvious your code belongs in the foo namespace, not merely uses it. Unlike option two, it saves lots of typing. Win-win.
I'd rather go for the first case, where namespaces are explicitly marked:
namespace TheNamespace {
void TheClass::TheMethod() {
// code
}
}
The reason is that it is clear from that syntax that TheClass is a class and TheNamespace is a namespace (not so obvious by any other names). If the code were
void TheNamespace::TheClass::TheMethod() {
// code
}
then a reader does not clearly see whether TheNamespace is a namespace, or a class with an inside class by the name of TheClass.
class TheClass1
{
class TheClass2
{
void TheMethod();
}
};
void TheClass1::TheClass2::TheMethod() {
// code
}
I tend to avoid the 'using' statement, and even then the example by litb with two classes in two different namespaces will make both the compiler and the programmer confused and should be avoided.
I think it depends on each case. If it's a 3rd party library that's similar to your own code, and you want to avoid confusion in the code, then specifying the full namespace at each occurance may be beneficial. But other than that, less code is generally better (unless it becomes unclear).