6

I've always liked Python's

import big_honkin_name as bhn

so you can then just use bhn.thing rather than the considerably more verbose big_honkin_name.thing in your source.

I've seen two type of namespace use in C++ code, either:

using namespace big_honkin_name; // includes fn().
int a = fn (27);

(which I'm assured is a bad thing) or:

int a = big_honkin_name::fn (27);

Is there a way to get Python functionality in C++ code, something like:

alias namespace big_honkin_name as bhn;
int a = bhn::fn (27);
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953

6 Answers6

13
namespace bhn = big_honkin_name;

There's another way to use namespaces too:

using big_honkin_name::fn;
int a = fn(27);
rlbond
  • 65,341
  • 56
  • 178
  • 228
12

StackOverflow to the rescue! Yes you can. In short:

namespace bhn = big_honkin_name;
Community
  • 1
  • 1
Chris Lutz
  • 73,191
  • 16
  • 130
  • 183
6

It is easy..

namespace bhn = big_honkin_name;
yoco
  • 1,404
  • 1
  • 14
  • 19
2

You can use

using big_honkin_name::fn;

to import all functions named fn from the namespace big_honkin_name, so that you can then write

int a = fn(27);

But that doesn't let you shrink down the name itself. To do (something similar to but not exactly) that, you could do as follows:

int big_honkin_object_name;

You can later use:

int& x(big_honkin_object_name);

And thereafter treat x the same as you would big_honkin_object_name. The compiler will in most cases eliminate the implied indirection.

j_random_hacker
  • 50,331
  • 10
  • 105
  • 169
1
using namespace big_honkin_name;

Is not a bad thing. Not at all. Used judiciously, bringing namespaces into scope improves clarity of code by removing unnecessary clutter.

(Unless it's in a header file in which case it's very poor practice.)

But yes, as others have pointed out you can create a namespace alias:

namespace big = big_honkin_name;
MattyT
  • 6,531
  • 2
  • 20
  • 17
  • In fact I recall an expert recommending that in some obscure circumstance (that I can't recall) you *should* create a new block scope and use "using namespace XYZ;" before calling the unqualified `some_func()` in preference to calling `XYZ::some_func()`, since the former will interfere with name lookup less. Wish I could recall the specifics -- anyone? – j_random_hacker Sep 22 '09 at 07:59
1

Nicely put, C++ equivalent for Python imports are:

Python to C++

import someLib as sl => namespace sl = someLib;

from someLib import func -> using someLib::func;

from someLib import * -> using namespace someLib;

note that you must do the #include<someLib> in C++ before these.

the last one is quite famous!

#include<iostream>
using namespace std;
Community
  • 1
  • 1
Vin
  • 52
  • 1
  • 6