Better use of C++'s "using" keyword
DavidZemon
Posts: 2,973
I do quite like Java's import statement. I wish C++ had an equivalent, rather than using a preprocessor to pull in header files. Nonetheless, I feel that "using <namespace>::<class>" is a lot better than no "using" keyword or "using namespace <namespace>". I just found out that this is possible, so I have to share
I've just turned this code...
into this:
That's much better! And still much safer than "using namespace PropWare" at the top
I've just turned this code...
#include <PropWare/PropWare.h> #include <PropWare/gpio/pin.h> int main () { const PropWare::Pin led1(PropWare::Pin::Mask::P17, PropWare::Pin::Dir::OUT); led1.start_hardware_pwm(4); const PropWare::Pin led2(PropWare::Pin::Mask::P16, PropWare::Pin::Dir::OUT); while (1) { led2.toggle(); waitcnt(CLKFREQ / 4 + CNT); } }
into this:
#include <PropWare/PropWare.h> #include <PropWare/gpio/pin.h> using PropWare::Pin; int main () { const Pin led1(Pin::P17, Pin::Dir::OUT); led1.start_hardware_pwm(4); const Pin led2(Pin::P16, Pin::Dir::OUT); while (1) { led2.toggle(); waitcnt(CLKFREQ / 4 + CNT); } }
That's much better! And still much safer than "using namespace PropWare" at the top
Comments
If you like "import", have you ever looked at D? It's basically someone else's attempt at C++, and I think it does most things much better than C++ does. It uses import statements instead of header files. It has no preprocessor at all - instead, it has really powerful template system that's actually not a pain, unlike that of C++. Unfortunately, nobody uses it, AFAICT mostly because nobody else uses it.