Select a given namespace at runtime - c++

Say I have these namespaces:
namespace old
{
std::array<std::string,1> characters {"old"};
}
namespace young
{
std::array<std::string,1> characters {"young"};
}
Then I want the user to tell me at the beginning which version is he using. Then call the appropriate namespace throughout the program.
I have tried using namespace depending on input, but it doesn't work because I need to call the correct namespace in functions on other source files. I was thinking maybe can I send the namespace as a function parameter? Or do something clever with templates?
EDIT:
When I refer to "user" I mean somebody that is using my executable, a person playing my game.
What I want to do is to ask him the version he is going to use e.g. US version (things have some names), or UK version (things have other names).
All that changes is the names I use. But I want him to be able to switch between versions every time.
I hope it is clear, please let me know if you need further clarification.

There is no way to pass a namespace as function parameter or template parameter. User may use it as:
using namespace old;
characters[0] = 'O';
or code as:
old::characters[0] = 'O';
UPDATE: After updating original question
Namespaces are relevant during compile-time and do not reflect any behavior in runtime. What you need is more along the lines of:
enum Language
{
ENGLISH_UK, ENGLISH_US
};
std::array<std::string, 2> label = {
"colour", // for British-english
"color" // for US-English
};
And then in the code:
static Language lang = ENGLISH_UK;
std::cout << label[lang] << std::endl;
So, if there is a change in user interface, you do not need to recompile the whole app.

Short answer is no, because what functions are called and what variables are accessed at a particular location in your code when you e.g. write characters is detrmined at compile-time.
The slightly longer answer is that you can create wrapper functions and references in a separate namespace and let them forward to one or the other depending on the user (as long as the types are the same).
E.g.
namespace current {
int namespace_to_use = 1; // can be set by some initialization function in your code
std::array<std::string,1>& get_characters(){
return namespace_to_use == 0 ? old::characters : young::characters;
}
}
I wouldn't call that good application design and there are many more advanced/better versions of this (e.g. based on dynamic polymorphism and the factory pattern or pointers/references). What fits best depends on your needs and your level of expereience.

Related

Creating a sub-namespace with the name of another namespace

I want to do something like this:
namespace someModule
{
int someInt = 4;
}
namespace test::someModule
{
void f()
{
someModule::someInt = 2;
}
}
But it looks like the compiler searches for someInt in test::someModule and not in someModule. I could create test as test::someModule_, but it looks pretty ugly. Isn't there a better option?
you can always refer to the global namespace using :: as prefix, i.e.,
::someModule::someInt = 2;
Note that the fact you're having multiple identically named namespaces is probably pretty confusing! Unless you have a very good architectural reason that you explained why proposing to add such to a project I'm maintaining, I would reject this code – code like this is easy to misunderstand. In fact, it almost seems intentionally misleading! Your job as programmer is to write code that can be read and understood not only by machines, but also by yourself in a year or other developers tomorrow. When describing two different things (namespaces), use two different names. Using the same name is only fine if something does the same thing.

enum, classes, namespaces and long names

From what I understand, enums that relates to a class should be declared inside the class, like this:
namespace Sensors {
class MySensor {
public:
enum class SensorStatus {
kSensorActive,
kSensorInactive
}
SensorStatus GetCurrentStatus(void);
};
}
The problem I'm having with this, is that it leads to the following code in another part of the program.
Sensors::MySensor::SensorStatus current_status = mySensor.GetStatus();
switch (current_status):
case Sensors::MySensor::SensorStatus::kSensorActive: // 47 characters!
printf("Sensor is active.");
break;
case Sensors::MySensor::SensorStatus::kSensorInactive: // 49 characters!
printf("Sensor is inactive.");
break;
I appreciate that its very clear what kSensorActive and kSensorInactive refers to, no ambiguity there. But if you try to follow a style guide that specifies 80 characters, we end up with a lot of line breaks, which reduces clarity, IMHO. One example of a long line comes if we have a function that takes two different enumerators; MyFunction(NamespaceA::MyFirstClass::MyFirstEnum::AnEnumerator, NamespaceB::MySecondClass::MySecondEnum::ADifferentEnumerator) - a whopping 127 characters.
Is it common with these long names or am I missing something?
First, you repeat stuff:
The name kSensorActive doesn't have to say Sensor if you already specified that it's a SensorStatus in the name. Or you could remove Sensor from SensorStatus if it's inside MySensor. Maybe both.
The idea behind wrapping things inside classes and namespaces is that you CAN use the same name over and over again, for something that is "the same sort of thing", rather than having completely unique names throughout.
You can also, locally, change the names with using, something like this
using Status = Sensors::MySensor::SensorStatus;
and then us Status::kSensorActive where you previously used the long thing.
To reduce the length without reducing the overall scope clarity you have at least 2 options:
Alias types ie. using Status = Sensors::MySensor::SensorStatus;
A typedef ie. typedef Sensors::MySensor::SensorStatus Status2;
Use these inside the scope of this function so it is local and the ambiguous name doesnt spread throughout the code. Here is a live example.

D: finding all functions with certain attribute

Is it currently possible to scan/query/iterate all functions (or classes) with some attribute across modules?
For example:
source/packageA/something.d:
#sillyWalk(10)
void doSomething()
{
}
source/packageB/anotherThing.d:
#sillyWalk(50)
void anotherThing()
{
}
source/main.d:
void main()
{
for (func; /* All #sillWalk ... */) {
...
}
}
Believe it or not, but yes, it kinda is... though it is REALLY hacky and has a lot of holes. Code: http://arsdnet.net/d-walk/
Running that will print:
Processing: module main
Processing: module object
Processing: module c
Processing: module attr
test2() has sillyWalk
main() has sillyWalk
You'll want to take a quick look at c.d, b.d, and main.d to see the usage. The onEach function in main.d processes each hit the helper function finds, here just printing the name. In the main function, you'll see a crazy looking mixin(__MODULE__) - this is a hacky trick to get a reference to the current module as a starting point for our iteration.
Also notice that the main.d file has a module project.main; line up top - if the module name was just main as it is automatically without that declaration, the mixin hack would confuse the module for the function main. This code is really brittle!
Now, direct your attention to attr.d: http://arsdnet.net/d-walk/attr.d
module attr;
struct sillyWalk { int i; }
enum isSillyWalk(alias T) = is(typeof(T) == sillyWalk);
import std.typetuple;
alias hasSillyWalk(alias what) = anySatisfy!(isSillyWalk, __traits(getAttributes, what));
enum hasSillyWalk(what) = false;
alias helper(alias T) = T;
alias helper(T) = T;
void allWithSillyWalk(alias a, alias onEach)() {
pragma(msg, "Processing: " ~ a.stringof);
foreach(memberName; __traits(allMembers, a)) {
// guards against errors from trying to access private stuff etc.
static if(__traits(compiles, __traits(getMember, a, memberName))) {
alias member = helper!(__traits(getMember, a, memberName));
// pragma(msg, "looking at " ~ memberName);
import std.string;
static if(!is(typeof(member)) && member.stringof.startsWith("module ")) {
enum mn = member.stringof["module ".length .. $];
mixin("import " ~ mn ~ ";");
allWithSillyWalk!(mixin(mn), onEach);
}
static if(hasSillyWalk!(member)) {
onEach!member;
}
}
}
}
First, we have the attribute definition and some helpers to detect its presence. If you've used UDAs before, nothing really new here - just scanning the attributes tuple for the type we're interested in.
The helper templates are a trick to abbreviate repeated calls to __traits(getMember) - it just aliases it to a nicer name while avoiding a silly parse error in the compiler.
Finally, we have the meat of the walker. It loops over allMembers, D's compile time reflection's workhorse (if you aren't familiar with this, take a gander at the sample chapter of my D Cookbook https://www.packtpub.com/application-development/d-cookbook - the "Free Sample" link is the chapter on compile time reflection)
Next, the first static if just makes sure we can actually get the member we want to get. Without that, it would throw errors on trying to get private members of the automatically imported object module.
The end of the function is simple too - it just calls our onEach thing on each element. But the middle is where the magic is: if it detects a module (sooo hacky btw but only way I know to do it) import in the walk, it imports it here, gaining access to it via the mixin(module) trick used at the top level... thus recursing through the program's import graph.
If you play around, you'll see it actually kinda works. (Compile all those files together on the command line btw for best results: dmd main.d attr.d b.d c.d)
But it also has a number of limitations:
Going into class/struct members is possible, but not implemented here. Pretty straightforward though: if the member is a class, just descend into it recursively too.
It is liable to break if a module shares a name with a member, such as the example with main mentioned above. Work around by using unique module names with some package dots too, should be ok.
It will not descend into function-local imports, meaning it is possible to use a function in the program that will not be picked up by this trick. I'm not aware of any solution to this in D today, not even if you're willing to use every hack in the language.
Adding code with UDAs is always tricky, but doubly so here because the onEach is a function with its on scope. You could perhaps build up a global associative array of delegates into handlers for the things though: void delegate()[string] handlers; /* ... */ handlers[memberName] = &localHandlerForThis; kind of thing for runtime access to the information.
I betcha it will fail to compile on more complex stuff too, I just slapped this together now as a toy proof of concept.
Most D code, instead of trying to walk the import tree like this, just demands that you mixin UdaHandler!T; in the individual aggregate or module where it is used, e.g. mixin RegisterSerializableClass!MyClass; after each one. Maybe not super DRY, but way more reliable.
edit:
There's another bug I didn't notice when writing the answer originally: the "module b.d;" didn't actually get picked up. Renaming it to "module b;" works, but not when it includes the package.
ooooh cuz it is considered "package mod" in stringof.... which has no members. Maybe if the compiler just called it "module foo.bar" instead of "package foo" we'd be in business though. (of course this isn't practical for application writers... which kinda ruins the trick's usefulness at this time)

C++ namespace elements

I want to get namespace elements name and value... how can I do that?
I want to list names and values (edited)
example
namespace testns{
int stuff=4;
};
int index=0;
get_element_name(testns,index);
get_element_value(testns,int,index);
A namespace is just what it says on the box, a namespace. You can have the same namespace in many modules, how would you know how to index them? What is the one and only proper order? Namespaces are only to categorize elements, not to somehow magically allow them to be indexed.
C++ does not have any reflection facilities (I assume that is what you are looking for). You have to manually state what you want.
What you're trying to do is called reflection, and C++ doesn't have any language-level built-in way of doing this for you. There are only a few things that can be done, such as using the # operator within a #define, but then you're using #defines, which I bet is not what you want.
The closest thing you can functionally get is to write another program which reads your source, digs out the namespace information, then writes it to a header file you can #include somewhere else. The GCC-XML extension could be helpful in this regard, since it uses the G++ front end to parse the language, then outputs the syntax trees as XML, which you can read with any number of XML DOM parsers.
In order to access the variable stuff, you do this:
//Setting
testns::stuff = 10;
//Getting
int stuff_value = testsn::stuff;
The purposes of namespaces are to disambiguate between code which use similar nomenclature.

__COUNTER__ equivalent on Xcode?

I am migrating a project from Linux to Xcode and I encountered a "version" problem..
I need a unique identifier at compile time for my dynamic stuff, on linux I was using the __ COUNTER__ preprocessor, but it seems that the gcc 4.2 used in Xcode doesn't know about __ COUNTER__ yet...
So, I was wondering what I could do to solve this?
I can upgrade the GCC to 4.3(which understands __ COUNTER__), by using the macports.org or something like that... I am very noob on OSX and not very good on linux =[
or find another way to accomplish this, in the case, a method to give the function/variable an unique identifier. I tried with __ LINE__ but after few days, you end up declaring stuff on the same line on different files, and playing with that is just not that produtive...
Any help is appreciated!
Thanks,
Jonathan
I need to catalog all classes used in
a project, so these classes can be
created on the fly from within a
factory [...]
Short of using RTTI (which isn't a bad idea if you are allowed to do this; boost::any does this), how about just using the string for the class names? You can retrieve this through a macro.
#include <iostream>
#include <string>
using namespace std;
template <class T>
const char* my_type_id()
{
return "Unknown";
}
#define REGISTER_TYPE(some_type) \
template <> inline \
const char* my_type_id<some_type>() \
{ \
return #some_type; \
}
REGISTER_TYPE(int)
REGISTER_TYPE(std::string)
int main()
{
// displays "int"
cout << my_type_id<int>() << endl;
// displays "std::string"
cout << my_type_id<string>() << endl;
// displays "Unknown" - we haven't registered char
cout << my_type_id<char>() << endl;
}
Nicest thing with this approach is that you don't have to worry about problems across translation units or modules with this approach. Only thing you have to watch out for is name conflicts, in which case you can specify a namespace to help avoid them ("std::string" as opposed to simply "string", e.g.).
We use this solution as an alternative for boost::any which we provide through our SDK (and therefore can't use boost as it would require our users to have boost installed or for us to ship parts of boost in which case it could lead to conflicts for users who have different versions of boost installed). It's not as automatic as boost::any as it requires manual registration of supported types (closer to boost::variant in this regard), but doesn't require our SDK users to have RTTI enabled and works portably across module boundaries (I'm not sure if one can depend on RTTI to produce the same information across varying compilers, settings, and modules - I doubt it).
Now you can use these type-associated string IDs however you like. One example would be to use it to map creation functions to these string IDs so that you can create an instance of std::string, for example, through factory::create("std::string"); Note that this is a hypothetical case for demo purposes only as using a factory to create std::string would be rather odd.
#stinky472: I use a code close to what you wrote above...
My problem was that I was using a macro to declare the namespaces of a project, so by that, having the fullname of the class, like class c is in a::b::c.
What I did was changing my code to not rely on the namespaces itself, but add a new argument at the class macro declaration to tell what namespace it is using, like:
newclass(a::b, c): public d{
};
my problem with counter was that the namespaces were being used on lots of classes, thus, creating the same variable name within the namespaces macros, and by using the new way above, I don't need the counter anymore...
thanks for the help,
Jonathan