Creating A Typedef In C++ - c++

What Searching I've Done:
Hello, so typedefs are a new topic to me, and I have already read a page about them. (http://en.cppreference.com/w/cpp/language/typedef) But that's the best information I could find, the only problem is because I have no idea how it's working enough, I'm unable to rework it and use it for my situation.
Also, for the heads up; I'm trying to create a type like the 'App' type that you write when creating a CLR Form in C++. (Visual Studio) The only difference is it will be used for a different reason, so don't copy the code from it please.
My Code:
#pragma once
class Application {
public:
typedef class App; // Runnable C++ object (TEST PLEASE DON'T JUDGE)
private:
void Run(App myApp) { // ERROR: incomplete type is not allowed
}
};
How You Can Help Me:
Explain what a typedef is used for. (Examples will work)
Explain in what type I should create the 'App' type. (Eg. Class, String, Int, etc.) Or explain in what other way I can do so.
You can also just create an example with comments explaining.
Thanks for the help! I tried to keep this question real explainable and sleek.

In C++, typedef simply creates an alias for another type, such that referencing the new type is identical to referencing the original type.
// create a alias for the int type
typedef int my_new_type;
// here a and b have the same type
int a = 1;
my_new_type b = 1;
The above is a contrived example, generally the types you use typedef for would be more complex (like std::vector<std::pair<int, std::string>>). For your use case, I'm not sure a typedef is what you are looking for.

I think you're looking for
typedef Application App;
But I'm not sure why you don't just do
class Application {
private:
void Run(Application myApp) {
}
};
As for usage, one use for typedef is to define types whose underlying type may vary depending on the build configuration, target platform and compiler. For example if you are writing a game that will run on PS4 and XBOX One, you might be using two different compilers depending on which platform you are building for.
#if defined(MSVC)
typedef __int64 TInt64;
#elif defined(GCC)
typedef int64_t TInt64;
#endif
This allows more of your code to be platform-agnostic and abstracts away compiler/platform details making app code more readable and encapsulating the assumptions we're interested in. It also reduces codebase size and preprocessing which can improve your compile times.
// We can assume this will be exactly 64 bits on all our target platforms.
TInt64 myInt = 0x1000000000000000;
P.S. Although it doesn't cover typedefs in general Marshall Cline's C++ FAQ is an great resource for beginners and experts alike.

Related

List of member reflection in C++ [duplicate]

Is there a way to enumerate the members of a structure (struct | class) in C++ or C? I need to get the member name, type, and value. I've used the following sample code before on a small project where the variables were globally scoped. The problem I have now is that a set of values need to be copied from the GUI to an object, file, and VM environment. I could create another "poor man’s" reflection system or hopefully something better that I haven't thought of yet. Does anyone have any thoughts?
EDIT: I know C++ doesn't have reflection.
union variant_t {
unsigned int ui;
int i;
double d;
char* s;
};
struct pub_values_t {
const char* name;
union variant_t* addr;
char type; // 'I' is int; 'U' is unsigned int; 'D' is double; 'S' is string
};
#define pub_v(n,t) #n,(union variant_t*)&n,t
struct pub_values_t pub_values[] = {
pub_v(somemember, 'D'),
pub_v(somemember2, 'D'),
pub_v(somemember3, 'U'),
...
};
const int no_of_pub_vs = sizeof(pub_values) / sizeof(struct pub_values_t);
To state the obvious, there is no reflection in C or C++. Hence no reliable way of enumerating member variables (by default).
If you have control over your data structure, you could try a std::vector<boost::any> or a std::map<std::string, boost::any> then add all your member variables to the vector/map.
Of course, this means all your variables will likely be on the heap so there will be a performance hit with this approach. With the std::map approach, it means that you would have a kind of "poor man's" reflection.
You can specify your types in an intermediate file and generate C++ code from that, something like COM classes can be generated from idl files. The generated code provides reflection capabilities for those types.
I've done something similar two different ways for different projects:
a custom file parsed by a Ruby script to do the generation
define the types as C# types, use C#'s reflection to get all the information and generate C++ from this (sounds convoluted, but works surprisingly well, and writing the type definitions is quite similar to writing C++ definitions)
Boost has a ready to use Variant library that may fit your needs.
simplest way - switch to Objective-C OR Objective-C++. That languages have good introspection and are full-compatible with C/C++ sources.
also You can use m4/cog/... for simultaneous generation structure and his description from some meta-description.
It feels like you are constructing some sort of debugger. I think this should be doable if you make sure you generate pdb files while building your executable.
Not sure in what context you want to do this enumeration, but in your program you should be able to call functions from Microsofts dbghelp.dll to get type information from variables etc. (I'm assuming you are using windows, which might of course not be the case)
Hope this helps to get you a little bit further.
Cheers!
Since C++ does not have reflection builtin, you can only get the information be teaching separately your program about the struct content.
This can be either by generating your structure from a format that you can use after that to know the strcture information, or by parsing your .h file to extract the structure information.

CMap with CArray Inside it

I have a typedef struct like this:
typedef struct
{
int id;
CString name;
} USER_NAME;
CMap<int,int, CArray<USER_NAME>, CArray<USER_NAME>> * m_mUserNameMap;
In the CPP file:
CArray<USER_NAME> sUName;
sUName.id = 10;
sUName.name = "Test it!!!";
m_mUserNameMap = new CMap<int,int, CArray<USER_NAME>, CArray<USER_NAME>>;
m_mUserNameMap->SetAt(1, sUName);
I am getting following error:
error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject'
No idea what's going on!! Any help is welcome.
I tried making m_mUserNameMap not a pointer and that gives the above error in that line itself.
Using a CMap requires the value type to be copy-constructible and assignable but these operations are marked as private for CObject-derived classes such as CArray. That is why you get that error message.
You can't declare the map like you're attempting. What you can do is have the value type as a pointer. So then you'll add the address of the array to the map and not the array itself which would expect a copy.
CMap<int, int, CArray<USER_NAME> *, CArray<USER_NAME> *> *m_mUserNameMap;
However, ask yourself if you really must use MFC containers because the standard containers are an alternative that don't suffer from these limitations. Use MFC containers only if they're the obvious choice and make complete sense in the context of GUI code. Otherwise rely on the standard containers.
std::map<int, std::vector<USER_NAME>> *m_mUserNameMap;
However, ask yourself if you really must use MFC containers
I myself would say, yes. MFC is much preferred over standard lib. Two reasons:
---One example:
YouTube video: C++Now 2018: Z. Laine “Boost.Text: Fixing std::string, and Adding Unicode to Standard C++ (part 1)”
https://www.youtube.com/watch?v=944GjKxwMBo
--std::string is very inefficient, apparently. Also, it seems like the standard library suffers from lack of dedicated support... If they get around to fixing it, they will. Much like what happens in the Linux world.
---Another reason:
Forum thread posted in www.cplusplus.com:
Linux developers threaten to pull “kill switch”
http://www.cplusplus.com/forum/lounge/243067/
--While Linux is not the standard library... they are all open source resources... Too close for comfort, IMO.

C++ Calling different functions by string name

I am relatively new to C++ - I leanerd it some 6+ years ago, but have never really used it until some months ago.
What is the scenario:
Considerably large system with a lot of modules.
Desired Output:
Modules (namely X) "expose" certain functions to be called over network and have the result sent back to the caller (namely Y)
The caller Y doesn´t know any info about X, despite what was exposed by the library (function name and parameters).
The calling of function in X from the library will have to happen through a string received from Y - or a set of strings, as there will be parameters as well.
Ideally what I want to have is something as generic as possible with variable return/paramaters types, or some kind of type-erasure - owing to the fact that I don´t know which functions each module will want to expose. I reckon its quite utopic to get something like that running in C++. But hopefully with pre-determined possible return/parameter types, it is feasible. The communication is not a problem for now, what matters is what should be done in the module side.
Question:
Would it be possible to accomplish such thing using C++ and Boost ? I would be really greateful if someone could give me some guidelines - literature/tutorials/(pseudo)code examples and so on and so forth. I am ofc not expecting a full solution here.
Possible solution:
I am a little bit lost as to which "functionalities" of the languages I can/should use - mainly due to my restrictions in the project.
I thought about using Variadic Templates and found the question below, which really helps, the only problem is that Variadic Templates are not supported in VS2010.
Generic functor for functions with any argument list
After some extensive research in the Web, the closest answer I got was this:
map of pointers to functions of different return types and signatures
The scenario is pretty much the same. The difference, however, seems to me that the OP already knows beforehand the return/parameters the functions he will be using. Due to my low reputation (I just joined) I unfortunately cannot ask/comment anything there.
TBH I didn´t get that well how to accomplish what the selected answer explains.
Using maps is a way, but I would have to store objects which contains function pointers (as also answered in the question), but as it is possible to see in the provided code by the user, it does have some hard-coded stuff which I wasn´t desiring to have.
Further clarifications:
Yes, I am restricted to use C++ AND VS2010 SP1.
No, despite Boost, I cannot use any other 3rd library - it would be great to be able to use some Reflection libraries such as CPGF http://www.cpgf.org/ (even though I am not 100% sure if thats what I really need)
Minor Edit:
- Scripting language bindings (such as LUA) are indeed a way to go, yet I didn´t want to include it in the project.
I hope someone can shed light on this problem!
Thanking in advance for any input!
Looks like you're needed a little reflection module. For example we have a struct of method info such as:
struct argument_info {
std::string name;
std::string type;
std::string value;
}
struct method_info {
std::string method_name;
std::string return_type;
std::list<argument_info> arguments;
}
then compile a dll with all exported functions
extern"C" __declspec(dllexport) void f1(int a, int b){/*...*/}
extern"C" __declspec(dllexport) int f1(std::string a, int b, char* c){ return x; }
in the interpreter's code:
void call_function(method_info mi, argument_info& t_return)
{
/* let g_mi be a map, where key is a std::string name of the method and the
value is method_info struct */
if(!g_mi->find(mi.method_name))
throw MethodNotFindException
if(g_mi[mi.method_name].arguments.size() != mi.arguments.size())
throw InvalidArgumentsCountException;
for(int i = 0; i < g_mi[mi.method_name].arguments.size(); i++)
{
if(g_mi[mi.method_name].arguments[i].type != mi.arguments[i].type)
throw InvalidArgumentException;
}
t_return = module->call(mi.arguments);
}
I hope it may help you.

Which is more memory/performance efficient for static error strings, or are there alternatives?

I would like an opinion on what is the best way to handle static error strings in C++. I am currently using a number of constant char pointers, but they get unwieldy, and they are scatter every where in my code. Also should I be using static constant char pointers for these strings?
I was thinking about defines, hash tables, and INI files using the SimpleIni class for cross-platform compatibility. The project is an always running web server.
I would like to use error numbers or names to refer to them logically.
I am using the global space and methods contained in namespaced classes if that helps. The code is exported to C because of the environment if that helps as well.
Thanks
There are several things in tension here, so let me please enumerate them:
centralization / modularity: it is normal to think about centralizing things, as it allows to easily check for the kind of error one should expect and recover an error from an approximate souvenir etc... however modularity asks that each module be able to introduce its new errors
error may happen during dynamic initialization (unless you ban code from running then, not easy to check), to circumvent the lifetime issue, it is better to only rely on objects that will be initialized during static initialization (this is the case for string literals, for example)
In general, the simplest thing I have seen was to use some integral constant to identify an error and then have a table on the side in which you could retrieve other information (potentially a lot of it). For example, Clang uses this system for its diagnosis. You can avoid repeating yourself by using the preprocessor at your advantage.
Use such a header:
#define MYMODULE_ERROR_LIST \
ERROR(Code, "description") \
...
#define ERROR(Code, Desc) Code,
class enum ErrorCode: unsigned {
MYMODULE_ERROR_List
NumberOfElements
};
#undef ERROR
struct Error {
ErrorCode code;
char const* description;
};
Error const& error(ErrorCode ec);
And a simple source file to locate the array:
#define ERROR(Code, Desc) { Code, Desc },
Error const ErrorsArray[] = {
MYMODULE_ERROR_LIST
{ErrorCode::NumberOfElements, 0}
};
Error const& error(ErrorCode const ec) {
assert(unsigned(ec) < unsigned(ErrorCode::NumberOfElements) &&
"The error code must have been corrupted.");
return ErrorsArray[ec];
} // error
Note: the price of defining the macro in the header is that the slightest change of wording in a description implies a recompilation of all the code depending on the enum. Personally, my stuff builds much faster than its tested, so I don't care much.
This is quite an efficient scheme. As it respects DRY (Don't Repeat Yourself) it also ensures that the code-description mapping is accurate. The ERROR macro can be tweaked to have more information than just a description too (category, etc...). As long as the Error type is_trivially_constructible, the array can be initialized statically which avoids lifetime issues.
Unfortunately though, the enum is not so good at modularity; and having each module sporting its own enum can soon get boring when it comes to dealing uniformly with the errors (the Error struct could use an unsigned code;).
More involved mechanisms are required if you wish to get beyond a central repository, but since it seemd to suit you I'll stop at mentioning this limitation.
First of all, you can check other related questions on stackoverflow. Here you have some:
C++ Error Handling -- Good Sources of Example Code?
Exceptions and error codes: mixing them the right way
Then have a look at this great tutorial on error handling (it is a five parts tutorial, but you can access all of them from that link). This is especially interesting if you are using C++11, since it provides many more features for error handling. Alternatively you could use boost if you cannot use C++11.
You also need to consider whether you want to include support for localization. If your application may present messages to the users in different languages, it is better if you include that requirement from the very beginning in the error management too. You can check Boost.Locale for that, for instance.
I'd keep it simple, in a header:
enum ErrorCode { E_help, E_wtf, E_uhoh };
const char* errstr(ErrorCode);
Then in some .c or .cc file:
const char* error_strings[] = {
"help!",
"wtf?",
"uh-oh"
};
const char* errstr(ErrorCode e) { return error_strings[e]; }
Not a lot of detail in your question, but with what you've posted I would consider a singleton class for handling your error messages. You could create methods for accessing messages by code number or enum. Then you can implement internationalization or whatever else you need for your specific application. Also, if you do decide to use SQLite or some other file-based solution in the future, the class interface can remain intact (or be extended) minimizing impact on the rest of your code.

Enumerate members of a structure?

Is there a way to enumerate the members of a structure (struct | class) in C++ or C? I need to get the member name, type, and value. I've used the following sample code before on a small project where the variables were globally scoped. The problem I have now is that a set of values need to be copied from the GUI to an object, file, and VM environment. I could create another "poor man’s" reflection system or hopefully something better that I haven't thought of yet. Does anyone have any thoughts?
EDIT: I know C++ doesn't have reflection.
union variant_t {
unsigned int ui;
int i;
double d;
char* s;
};
struct pub_values_t {
const char* name;
union variant_t* addr;
char type; // 'I' is int; 'U' is unsigned int; 'D' is double; 'S' is string
};
#define pub_v(n,t) #n,(union variant_t*)&n,t
struct pub_values_t pub_values[] = {
pub_v(somemember, 'D'),
pub_v(somemember2, 'D'),
pub_v(somemember3, 'U'),
...
};
const int no_of_pub_vs = sizeof(pub_values) / sizeof(struct pub_values_t);
To state the obvious, there is no reflection in C or C++. Hence no reliable way of enumerating member variables (by default).
If you have control over your data structure, you could try a std::vector<boost::any> or a std::map<std::string, boost::any> then add all your member variables to the vector/map.
Of course, this means all your variables will likely be on the heap so there will be a performance hit with this approach. With the std::map approach, it means that you would have a kind of "poor man's" reflection.
You can specify your types in an intermediate file and generate C++ code from that, something like COM classes can be generated from idl files. The generated code provides reflection capabilities for those types.
I've done something similar two different ways for different projects:
a custom file parsed by a Ruby script to do the generation
define the types as C# types, use C#'s reflection to get all the information and generate C++ from this (sounds convoluted, but works surprisingly well, and writing the type definitions is quite similar to writing C++ definitions)
Boost has a ready to use Variant library that may fit your needs.
simplest way - switch to Objective-C OR Objective-C++. That languages have good introspection and are full-compatible with C/C++ sources.
also You can use m4/cog/... for simultaneous generation structure and his description from some meta-description.
It feels like you are constructing some sort of debugger. I think this should be doable if you make sure you generate pdb files while building your executable.
Not sure in what context you want to do this enumeration, but in your program you should be able to call functions from Microsofts dbghelp.dll to get type information from variables etc. (I'm assuming you are using windows, which might of course not be the case)
Hope this helps to get you a little bit further.
Cheers!
Since C++ does not have reflection builtin, you can only get the information be teaching separately your program about the struct content.
This can be either by generating your structure from a format that you can use after that to know the strcture information, or by parsing your .h file to extract the structure information.