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.
Related
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.
I am new to coding and C++ and I am asking myself how to store or structure all these little (sub)functions and code in a proper way?
For example a function to sum up all values of an array or the Fibonacci numbers or all the other little functions and programs which are basic stuff esp. pointers etc.!?
My idea is to create an ordinary .txt sheet and to copy and paste them all there in just one .txt
For me it´s important to have them all at one place. How do you pros handle this or do you guys really have most of this stuff in your local memory (brain). For me it seems impossible to remember all the functions and algorithms or even the syntax (when the code starts to get nasty).
If I understood your question correctly then you are asking where/how we store reusable snippets of code in an easy to access way. There are number of methods to accomplish this, one which you have mentioned is to simply use a text file and copy paste as needed, but in my opinion this is a bit archaic.
I have two main methods I like to use, first if it's code I want to access online or is rather large functions I plan to reuse, I simply make a gist of it and leave it there, ready to be accessed as needed. Usually I name it something descriptive so when I look through all my gists, I can find the ones I need quickly.
The second method, and the stuff I do for code that mainly gets reused is to make snippets using my IDE's configuration files. Such snippets usually are written in JSON format and include a trigger word, for example: for and then when you hit a special key, typically tab, it will expand the snippet to something like:
for(int i = 0; i < n; i++) {
// Code goes here...
}
And we can simply just hit tab to edit the starting condition, the ending condition, the increment and the variable names. Snippets are very versatile and you can write as many as you want. If you use Visual Studio Code you can take a look at the C++ tools extension which has some default snippets.
Lastly I keep a handy bookmark to a C++ reference site and look up stuff in the STL as needed so I'm not reinventing the wheel or making extra work for myself.
Welcome to StackOverflow!!!
In C++ you generally put all your functions in a header and cpp file to store all the functions. You then go to the main and pick up a reference to the header file.
// A2DD.h
#ifndef A2DD_H
#define A2DD_H
namespace A2DD{
int GetSum(int x, int y);
}
#endif
and the implementation goes in the CPP file:
// A2DD.cpp
#include "A2DD.h"
int A2DD::GetSum(int x, int y){
return x + y;
}
Then go the main.cpp
#include "A2DD.h"
int main(){
std::cout << GetSum(2, 2) << std::endl;
}
As far as remembering the functions, you can simply take a quick look at the header file which declares the functions (no implementation)
This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 8 years ago.
using namespace std;
So far in my computer science courses, this is all we have been told to do. Not only that, but it's all that we have been allowed to do, otherwise we get penalized on our code. I understand, through looking at code posted online, that you can use ::std or std:: to accomplish the same thing.
My question is generall why? Obviously for the sake of learners and simplicity using the global declaration is simpler, but what are the draw backs? Is it more realistic to expect ::std in a real world application? And I guess to add on to this, what is the logic/concept behind the using declaration? None of this has been explained during my courses, and I'd like to get a better grasp on it.
As a general question: if I haven't been taught this content, vectors, templates, classes, or error handling does it seem like I'm missing a lot of essential C++ functionality?
Thanks in advance!
This is really one of those things that you can discuss over beer for hours and hours, and still not have an answer everyone is happy with.
If you are nearly always using std:: functionality, then adding using namespace std; at the beginning of the file is not that bad an idea. On the other hand, if you are using things from more than one namespace (e.g. writing a compiler using llvm:: and also using std::, it may get confusing as to which parts are part of llvm and which parts are std:: - so in my compilter project, I don't have a single file with using namespace ...; - instead I write out llvm:: and std:: as needed. There are several functions (unwisely, perhaps) called Type(), and some places use something->Type()->Type() to get the type-thing that I need... Yes, it confuses even me a little at times...
I also have many things that look like Constants::ConstDecl and Token::RightParen, so that I can quickly see "what is what". All of these COULD be made shorter and "simpler", but I prefer to see where things belong most of the time.
Being more verbose helps making it easier to see where things belong - but it makes for more typing and more reading, so it is a balance.
I'd say that generally, you do not declare the use of std globally. I guess if you're making a simple application, that would suffice. However, when you work in a large organization you often times have different namespaces that are used, and those might have overlapping objects. If you have a function in std, and in a namespace that you created, and then call "using namespace std" AND "using namespace yournamespace", you'll get unwanted results when calling that function. When you prefix every call with the namespace, it keeps it clearer and doesn't give issues with overlap.
general why?
Naming things is one of the more difficult aspects of software development. Beginners simply have little idea of how their name choices might generate ambiguities later on.
In particular, our software jargon often has preferred terms for certain issues. These preferences can cause unrelated class instances to be developed with the same (or similar) symbol with similar meanings.
Some of my often used symbols include init(), exec(), load(), store(), and I use timeStampGet() lots of places. I also use open(), close(), send()/recv() or write()/read().
So, I could rename init() in each of the 3 name spaces, and 5 objects into which I have added it, but it is much simpler to specify which one I want.
I find exec() in 2 name spaces and 12 objects. And there are 3 different timeStampGet() methods that I use. Whether namespaces or functions or class methods, these symbols make sense to me.
Furthermore, I find the 5 char "std::" namespace-as-prefix completely natural, and much preferable to the global "using namespace std". I suppose this comes with practice.
One more item - any where a larger name space or class name becomes tiresome, I sometimes add a typedef short name ... here are some examples from production code:
typedef ALARM_HISTORY ALM_HST;
typedef MONITOR_ITEM MI
typedef BACKUP_CONTROL BC;
On one team, we agreed to use well defined 'full' names, which, occasionally, became tiresome because of the length. Later in the project, we agreed that typedefs (for short class or namespace names) could be used when they were simple and added no confusion.
Personally I hate 'using' declarations. To me they make code unreadable and you break namespaces. I've spent 20 years as a maintenance programmer and I hate anything that make the code harder to read - in my mind using is as useless as throw specifications.
What is more readable 6months - a year - 10 years down the line
UDP::Socket sock
sock.send(data)
TCP::Socket sock2
sock2.send(data)
vs
using UDP;
using TCP;
sock.send(data)
sock2.end(data)
I also don't like namespace aliases
using namespace po = boost::program_options;
Now you are making the next programmer work harder with an extra level of indirection looking up what po is compared to boost::program_options. Same goes for those horrible typedef of
typedef long QUADWORD;
What size is a quadword - how long is a long 4 bytes? 8 bytes maybe 17 bytes on my OS
My last take is if you cannot type then don't be a programmer - a saved keystroke != good maintainable code
I need to parse a C++ class file (.h) and extract the following informations:
Function names
Return types
List of parameter types of each function
Assume that there is a special tag using which I can recognize if I need to parse a function or not.
For eg.
#include <someHeader>
class Test
{
public:
Test();
void fun1();
// *Expose* //
void fun2();
};
So I need to parse only fun2().
I read the basic grammar here, but found it too complex to comprehend.
Q1. I can't make out how complex this task is. Can someone provide a simpler grammar for a function declaration to perform this parsing?
Q2. Is my approach right or should I consider using some library rather than reinventing?
Edit: Just to clarify, I don't have problem parsing, problem is more of understanding the grammar I need to parse.
A C++ header may include arbitrary C++ code. Hence, parsing the header might be as hard as parsing all kinds of C++ code.
Your task becomes easier, if you can make certain assumptions about your header file. For instance, if you always have an EXPOSE-tag in front of your function and the functions are always on a single line, you could first grep for those lines:
grep -A1 EXPOSE <files>
And then you could apply a regular expression to filter out the information you need.
Nevertheless, I'd recommend using existing tools. This seems to be a tutorial on how to do it with clang and Python.
GCC XML is an open source tool that emits the AST (Abstract Syntax Tree). See this other answer where I posted about the usage I made of it.
You should consider to use only if you are proficient (or akin to learn) with an XML analyzer for inspecting the AST. It's a fairly complex structure...
You will need anyway to 'grep' for the comments identifying your required snippets, as comments are lost in output XML.
IF you are doing this just for documentation doxygen could be a good bet.
Either way it may give you some pointers as to how to do this.
I have the need to parse partial XML fragments (which are presented as std::string), such as this one:
<FOO:node>val</FOO:node>
as xmlDoc objects in libxml2, and because these are fragments, I keep getting the namespace error : Namespace prefix FOO on node is not defined errors spit out into STDERR.
What I am looking for is for either a way to filter just these namespace warnings out or parse the XML fragment straight into a xmlNode object.
I think some sort of hacking around with initGenericErrorDefaultFunc() may be in order to go the first way, but the documentation for libxml2 is absolutely atrocious.
I would frankly prefer to go with the 2nd approach because it would require no error hacking and the node would be already aware of the namespace, but I don't think it's possible because the node has to have a root and XML fragments are not guaranteed to have only one root.
I just need some guidance here of how to rid myself of the namespace error warning.
Thank you very much.
Building on what #Potatoswatter said... can you create a context for the fragments? E.g. concatenate
<dummyRoot xmlns:FOO="dummy-URI">
in front of your fragment, and
</dummyRoot>
afterward, then pass the concatenated string to xmlParseMemory().
Alternatively, why don't you use xmlParseInNodeContext(), which lets you pass in a node to use as context (including namespaces), and the content can be any Well Balanced Chunk (e.g. multiple elements with no single root element).
Either method requires that you know, or can scan to find out, the set of all possible namespace prefixes that the fragment may use.
Is it not an option to pass the xmlParserOptions XML_PARSE_NOERROR and/or XML_PARSE_NOWARNING to the parser?