I've often found myself wanting a way to undo the effect of a using statement or to include all of a namespace (such as std) but exclude a bit to be replaced (such as cout). For some reason this isn't possible. I am wondering if anyone knows why it was decided not to add this ability to the language? Is there some technical reason? I assume it wasn't just forgotten since it doesn't seem slated for C++0x either.
Just to clarify, I'm not looking for workarounds since Google can show me those. I'm looking for an explanation of why this is impossible, and why it was not considered (as far as I can tell) for inclusion in 0x.
A using directive brings a name or set of names into a given declarative scope.
You can't "un-using" for the same reason that you can't say
int x = 42;
// and later
[remove name x somehow]
There's no way to unintroduce names from a scope at all in C++, regardless where those names came from.
Given that it would overcomplicate name lookup (since names could be both added and removed from a scope), unless there is a really compelling use case, it's unlikely to be considered as a potential language feature.
This is because the using directive is not meant to be used for native C++ code. It was intended to help migrate C code to C++. In this context, "un-using" doesn't make sense.
-edit-
I should have been more specific. In this particular case, it looks like mstearn is using the using directive to include the std namespace globally. Doing this is generally a bad idea because it results in global namespace pollution, and should only be done in certain circumstances, like transitioning from another language to C++.
There are other situations where utilizing the using directive is fine (within a function, namespace composition). However "un-using" doesn't make sense in these situations either.
Mostly because there are workarounds that are sufficiently simple and straightforward that virtually nothing would be gained by including a "feature" for that specific purpose. Though I'm not sure he ever states it directly, I think you could argue that one of the guidelines in the design of C++ has always been to prefer general mechanisms to special-purpose ones, so using the existing scope system (for example) makes more sense than adding some special way to remove something from a scope after it's been introduced.
Related
I figured one of the best ways I could learn and improve in programming is to look at various source codes. I was looking at Blender's source code and noticed something about the header files. Most of them used #ifndef include guards, where macros were surrounded by double underscores (e.g. __BMESH_CLASS_H__).
It got me thinking, the whole "just don't make anything that starts with underscores at all" advice is good for beginners, but I would think that in order to progress further in programming I should learn when creating my own reserved identifiers is and isn't appropriate.
I would think that in order to progress further in programming I should learn when creating my own reserved identifiers is and isn't appropriate.
Reserved identifiers are reserved for the implementation, which means roughly the compiler, its runtime library, and maybe parts of the operating system.
So, it's appropriate to create your own when your progression has led to you writing your own compiler or operating system. That's pretty much it.
There is only one case I know of where reserved identifiers are allowed to be self-made. All others are considered undefined behavior, and while they will still most likely work completely the same, it's against the standard and shouldn't be done.
That said, reserved identifiers can be made by you when interacting with certain components of your development environment. For example, some compilers may support something like __FILE_NAME__ and others may not, and it may even vary from compiler version to compiler version. If you are making it yourself for, say, backwards compatibility (i.e. adding a preprocessor definition to define said macro), then it is 100% okay, so long its implementation follows the requirements of what is expected of using said identifier exactly (e.g. it should substitute to the file name for __FILE_NAME__, not something else).
Coming from a c# and java background, namespaces are nothing new to me and I have come to love the organizational structuring it brings to code.
I've been doing more work in c++ lately and I try to keep my coding habits as modern as possible. I have been toying around with some sandbox code, trying some new things and I would like to get some feedback on something I've been playing around with.
What I did was create a header file that explicitly declares a series of structured namespaces. The reason I did this is I wanted to layout a predefined structuring for namespaces to be used in the project. I realize that obviously the namespaces could be declared within any classes as the classes are defined but I like the idea of predefined structuring of the namespaces, such as (just an example):
namespace System
{
namespace IO
{
}
namespace Serialization
{
}
namespace Security
{
namespace Cryptography
{
}
}
}
etc. You get the idea.
My question is: Is there anything wrong with this approach? I figured it could be a good practice since it follows good coding practices with encapsulation and naming, etc.
I have seen some strange comments about similar things by old-school c++ devs, such as: "You're trying to combine Java and c++", or "Namespaces are just a way to mangle type names to avoid naming conflicts". I completely disagree with those opinions and don't feel those people are fully understanding the utility that namespaces can provide.
I don't think there's anything inherently "wrong" with it: you're documenting the intended structure of your namespaces.
But, ultimately, it's also pretty pointless, since nothing about this file stops namespaces with the same names from being [accidentally] created in a different structure, leaving you with a broken hierarchy there with actual types declared in it, and your intended hierarchy here with nothing at all in it.
Consequently I'd probably stick to standalone documentation for this sort of thing.
Declaring a namespace hierarchy in a header file is not very useful in practice; including the header file in any other files has no effect.
It seams to me you are trying to create a rule for people working on that project to follow, which or may or may not stick...it's all a matter of style and preference.
But there is nothing wrong with the approach it can do no harm.
I have read in several places that single segment namespaces are discouraged in clojure.
Indeed almost every library I've seen has (require 'lib.core) instead of (require 'lib).
Why?
Edit: I am a bit stupid. Extra credit will be given for a concise example of how a single segment namespace might be a bad thing.
Java discourages the use of the default package because you can't refer to anything in it from any other package. If you pre-compile a one-segment Clojure namespace, you'll get a Java class in the default package. If anyone at any time wants to use your library from Java, he will be stopped dead by this triviality. As there is no good reason in favor of using a single-segment namespace, and there is this one well-defined reason not to, it is fair to say that single-segment namespaces should be a discouraged practice in Clojure.
Single segment namespaces have issues with Java interop. Some things may break in unexpected ways. See also https://groups.google.com/forum/?fromgroups=#!topic/clojure/gOffhotk25Y
In C++ it is possible to use the static keyword within a translation unit to affect the visibility of a symbol (either variable or function declaration).
In n3092, this was deprecated:
Annex D.2 [depr.static]
The use of the static keyword is deprecated when declaring objects in namespace scope (see 3.3.6).
In n3225, this has been removed.
The only article I could find is somewhat informal.
It does underline though, that for compatibility with C (and the ability to compile C-programs as C++) the deprecation is annoying. However, compiling a C program directly as C++ can be a frustrating experience already, so I am unsure if it warrants consideration.
Does anyone know why it was changed ?
In C++ Standard Core Language Defect Reports and Accepted Issues, Revision 94 under 1012. Undeprecating static they note:
Although 7.3.1.1 [namespace.unnamed] states that the use of the static keyword for declaring variables in namespace scope is deprecated because the unnamed namespace provides a superior alternative, it is unlikely that the feature will be removed at any point in the foreseeable future.
Basically this is saying that the deprecation of static doesn't really make sense. It won't ever be removed from C++. It's still useful because you don't need the boilerplate code you would need with unnamed namespace's if you just want to declare a function or object with internal linkage.
I will try to answer your question, although it is an old question, and it does not look very important (it really is not very important in itself), and it has received quite good answers already. The reason I want to answer it is that it relates to fundamental issues of standard evolution and language design when the language is based on an existing language: when should language features be deprecated, removed, or changed in incompatible ways?
In C++ it is possible to use the static keyword within a translation unit to affect the visibility of a symbol (either variable or function declaration).
The linkage actually.
In n3092, this was deprecated:
Deprecation indicates:
The intent to remove some feature in the future; this does not mean that deprecated features will be removed in the next standard revision, or that they must be removed "soon", or at all. And non-deprecated features may be removed in the next standard revision.
A formal attempt to discourage its use.
The latter point is important. Although there is never a formal promise that your program won't be broken, sometimes silently, by the next standard, the committee should try to avoid breaking "reasonable" code. Deprecation should tell programmers that it is unreasonable to depend on some feature.
It does underline though, that for compatibility with C (and the ability to compile C-programs as C++) the deprecation is annoying. However, compiling a C program directly as C++ can be a frustrating experience already, so I am unsure if it warrants consideration.
It is very important to preserve a C/C++ common subset, especially for header files. Of course, static global declarations are declarations of symbol with internal linkage and this not very useful in a header file.
But the issue is never just compatibility with C, it's compatibility with existing C++: there are tons of existing valid C++ programs that use static global declarations. This code is not just formally legal, it is sound, as it uses a well-defined language feature the way it is intended to be used.
Just because there is now a "better way" (according to some) to do something does not make the programs written the old way "bad" or "unreasonable". The ability of using the static keyword on declarations of objects and functions at global scope is well understood in both C and C++ communities, and most often used correctly.
In a similar vein, I am not going to change C-style casts to double to static_cast<double> just because "C-style casts are bad", as static_cast<double> adds zero information and zero safety.
The idea that whenever a new way to do something is invented, all programmers would rush to rewrite their existing well-defined working code is just crazy. If you want to remove all the inherited C ugliness and problems, you don't change C++, you invent a new programming language. Half-removing one use of static hardly makes C++ less C-ugly.
Code changes need a justification, and "old is bad" is never a justification for code changes.
Breaking language changes need a very strong justification. Making the language very slightly simpler is never a justification for a breaking change.
The reasons given why static is bad are just remarkably weak, and it isn't even clear why not both objects and function declarations are deprecated together - giving them different treatment hardly makes C++ simpler or more orthogonal.
So, really, it is a sad story. Not because of the practical consequences it had: it had exactly zero practical consequences. But because it shows a clear lack of common sense from the ISO committee.
Deprecated or not, removing this language feature would break existing codes and annoy people.
The whole static deprecation thing was just wishful thinking along the lines of "anonymous namespaces are better than static" and "references are better pointers". Lol.
Lately as part of my day job I've been learning IBM Rhapsody and using it to generate code in C++ from the UML.
Yesterday it struck me that it might be cool to think about adding state machine support to my C++ compiler, so I jotted a few notes here: http://ellcc.org/wiki/index.php/State_machines_and_Active_Classes
My motivations for doing this are:
It seems like a cool idea.
The compiler could do much better semantic checking (with better error checking) than the current Rhapsody/normal C++ compiler.
There are many optimization possibilities available when the compiler itself understands the state machine structure.
I may try to extend my grammar to except something like the proposal to see how well it works.
What is your opinion of the proposal? Does it seem readable? Does it seem worthwhile?
Edit:
Thanks for the answers recommending specific libraries to do state machines, but that wasn't my question. I've implemented many state machines using both libraries and code that I've written.
I was really looking for ideas, criticism, etc. about the design of a state machine extension to a C++-like language, not whether this change would be appropriate for addition to standard C++. Think of it as a domain specific extension, where my my domain is real-time control applications.
I've started implementation of the extension in my compiler as described here: http://ellcc.org/wiki/index.php/State%5Fmachines%5Fand%5FActive%5FClasses
So far the concept hasn't had to change much going from proposal to implementation but there have been a few changes in details and I'm refining my understanding of the semantics of the problem.
Time will tell whether the whole concept has any value, however. ;-)
With a few exceptions, C++ has traditionally been extended using class libraries, not new keywords. State machines can easily be implemented using such libraries, so I don't think your proposal has much of a chance.
One problem I see in your proposal is the use of 'goto' to go to another state. What happens if I want to use goto in my own code within a state transition?
Excellent work developing what you've done. Something like you've done probably is possible, but I'm doubtful it would ever get into the C++. Most changes that make it into the language itself are included only to allow people to write more useful and powerful libraries.
There's a library here that provides support for state machines. I haven't tried it, but it might interest you, and you may be able to combine your ideas with a library like this to allow other people to make use of it.
http://www.boost.org/doc/libs/1_34_1/libs/statechart/doc/index.html
Or, you could develop your own extension as you suggest, and it would at least be useful for you. Microsoft implement some extension keywords, so there is no reason why you couldn't create your own extended version of C++.
Keep the new ideas coming.
You should take a look at how another smart developer added State machine support to a C-like language: UnrealScript Language Reference. See the section named "States".
UnrealScript supports states at the
language level. In UnrealScript, each
actor in the world is always in one
and only one state. Its state reflects
the action it wants to perform. For
example, moving brushes have several
states like "StandOpenTimed" and
"BumpOpenTimed". Pawns have several
states such as "Dying", "Attacking",
and "Wandering". In UnrealScript, you
can write functions and code which
exist in a particular state. These
functions are only called when the
actor is in that state
It's an interesting idea, but I think you'd actually have better luck creating your own domain-specific language for state machines than officially extending C++. C++ is designed as a very general-purpose programming language. I think Boost has proven that C++ is flexible enough that most features can be implemented nicely using libraries. It also evolves very slowly, to the extent that standard C++ still doesn't even have built-in threading support as of 2009, (it is planned in 0x). So it's unlikely the committee would consider this addition for some time.
Your solution does not look like it has any advantages to a template- or preprocessor-macro-based solution.
I am also not sure, how you can provide better semantic checking. And I doubt that you can apply many useful code optimizations.
However, to allow better optimizations and semantic checking, you should also replace "goto" with a new keyword (e.g. __change__ newState), and disallow goto for state changes! Allow goto for local jumps as usual.
Then the compiler can extract a list of possible transitions.
Read your proposal, have the following comments:
There's actually no keyword to declare and define an actual state machine! Do you assume a single global state machine (and thus a single global state)? How does that relate to __active__ ?
The closest comparable construct in C++ is actually the enum. Why not extend it?
There seems to be some connection between defined events and states, but I fail to see how it's implemented.
Why are threads and timers needed at all? Some use cases of state machines may benefit from them, but a good proposal should keep these seperate. Most importantly this should allow the use of standard C++0x threads.
Personally, I would extend the enum syntax:
enum Foo {
red, blue, green; /* Standard C++ so far - defines states. State list ends with a ; not a , */
Foo() { *this = red; } // Reuse ctor syntax, instead of __initial__
~Foo() { } // reuse dtor syntax, instead of __onexit__
void Bar() {/**/} // Defines an event, no return value. Doesn't need keyword __event__
};
It follows naturally that you can now declare your events in a header, and define them in a .cpp file. I don't even need to suggest the syntax here, any C++ programmer can guess that at this point. Add a bit of inheritance syntax for combined states:
enum DrawingObject : public Shape, public Color { /** } // allows (red && circle)
and you're pretty much at the point where your proposal is, without any new keywords, all by reusing an already familiar syntax.