Question

I have

namespace src {
   struct src_bar;
   void src_baz();
   template<class T> class src_qux;
}

which I'd like to reference as

namespace dst {
    struct dst_bar;
    void dst_baz();
    template<class T> class dst_qux;
}

meaning that I'd like to "rename" or "alias" or "relabel" names from src.

For dst_bar one can of course use namespace dst { typedef src_bar dst_bar; }. Is there some (non-macro) equivalent allowing me to rename src::src_baz as dst::dst_baz and src::src_qux as dst::dst_qux?

Unless I'm mistaken, neither a using statement nor a namespace alias can accomplish the other two. Writing templated forwarding functions for dst_baz() is a possibility but requires knowledge of the arity of src_baz. Template typedefs could have dst_qux<T>::type be src_qux<T> but the indirection adds verbosity.

FWIW, my use case is taking C names like somepackage_someportion_somefuncA and providing a namespaced-friendly version somepackage::someportion::somefuncA so that other folks can employ using somepackage::someportion for brevity.

Was it helpful?

Solution

For functions you will have to manually forward the requests. For non-template types you can just typedef. For template types, y can use the new using feature of c++11 To create a typedef-style alias for a template, if your compiler supports it, or else you are basically out of luck.

OTHER TIPS

No, you cannot "rename" something so that it no longer uses its original name.

However, you can get the same effect via trickery.

First, import the header for the defines you want to corral inside a namespace block:

namespace foo {
    #include "src_stuff.h"
}

Now you have foo::src::src_bar and friends.

Then, use typedef liberally:

namespace bar {
    typedef foo::src::src_bar dst_bar;
}

Voila, you've got a bar::dst_bar which is the same as src::src_bar would have been. If you don't care about the definitions remaining available under the old names in addition, skip the first step and just make typedefs for convenience. That's what they're for, after all.

If usage of macros is an acceptable option for you then here is one solution:

// declare this macro in some common file
#define CREATE(SCOPE) \
namespace SCOPE { \
   struct SCOPE## _bar; \
   void SCOPE## _baz(); \
   template<class T> class SCOPE## _qux; \
}

Usage:

CREATE(src);
CREATE(dst);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top