Shop OBEX P1 Docs P2 Docs Learn Events
Better use of C++'s "using" keyword — Parallax Forums

Better use of C++'s "using" keyword

DavidZemonDavidZemon Posts: 2,973
edited 2016-10-17 02:30 in Learn with BlocklyProp
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 :D

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

  • ElectrodudeElectrodude Posts: 1,660
    edited 2016-10-17 05:07
    Wow, I might actually use that. I've always stayed away from "using namespace <namespace>" after I read this answer on StackOverflow about someone who got bit by "using namespace std;". This is much better, though.

    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.
  • TorTor Posts: 2,010
    D is interesting. As you say, the problem is the low user base, which is what keeps the user base low. But to me it's much more appealing than C++. It's even a better C, unlike C++.
  • I have heard of D. Heard about it a few years ago and almost never since! Exactly like you said, seems like nobody is using it because nobody is using it. That's a terrible position to be in :(
Sign In or Register to comment.