I have a map, where string representing the name of attribute and the second value representing the type, which this attribute should have.
map.insert(make_pair("X", iDatatype::iUint));
map.insert(make_pair("Y", iDatatype::iUint));
map.insert(make_pair("RADIANT", iDatatype::iFloat));
where iDatatype is just enumeration of all possible types.
typedef enum
{
iUnknown = 0,
iByte = 1,
iChar = 2,
iUChar = 3,
iShort = 4.....
} iDatatype;
If the program gets the command to create, for example, "RADIANT" than it look at the map, find the iDatatype value (iter->second) and go to switch case.
switch (iter->second) {
case iDatatype::iUint:
uint value = ......
// You gotta do what you gonna do
break;
} .......
In Switch case, the function, which depends on type of attribute, will be called.
This code works. But I am not sure, if it the best solution to map string with the types.
And the problem that I don't know what should I look for? Could you recommend what methods or techniques are commonly used for such purpose? Thank you a lot.
Unless you need the map for some other reference, another approach will be:
if(command == "X" || command == "Y") // make sure command is std::string
// or use strcmp
{
// create uint
}
else if(command == "RADIANT")
{
// create float
}
However I'm not sure how much faster this will be than using a map, because a map uses binary search while this uses iterative search.
If you want to gain the boost of binary search while no need for another enum you can use a map of functions:
std::map<std::string, std::function<void()> map;
map.insert(make_pair("X", &create_uint));
map.insert(make_pair("Y", &create_uint));
map.insert(make_pair("RADIANT", &create_float));
and later call it like:
std::string key = "X";
map[key]();
you can also pass parameters to it like:
void create_uint(std::string param) { /* ... */ }
std::map<std::string, std::function<void(std::string)> map;
map.insert(make_pair("X", &create_uint));
std::string key = "X";
std::string param = "XYZ";
map[key](param);
Related
I have this code:
enum EXECUTION_COMMANDS {
"buy" = OP_BUY,
"sell" = OP_SELL,
"buyLimit" = OP_BUYLIMIT,
"sellLimit" = OP_SELLLIMIT,
"buyStop" = OP_BUYSTOP,
"sellStop" = OP_SELLSTOP
};
So basically what I want to create is when program sees the string "buy", it has to read it as OP_BUY. Since OP_BUY is an internal command on MQL4, how do I do this? Is there another way to do this?
enum EXECUTION_COMMANDS
{
buy = OP_BUY,
...
};
Now the identifier buy is basically a named integer constant with the same value as OP_BUY. You can use buy and OP_BUY as aliases for each other.
If you really want to use strings then you need to create a map, that maps the strings into their integer values:
std::unordered_map<std::string, int> command_map = {
{ "buy", OP_BUY },
...
};
Then to use it use command_map["buy"] which will return the int value of OP_BUY.
Just take out the quotes.
The names of the enumerators should be identifiers, not strings.
enum EXECUTION_COMMANDS
{
buy = OP_BUY,
sell = OP_SELL,
buyLimit = OP_BUYLIMIT,
sellLimit = OP_SELLLIMIT,
buyStop = OP_BUYSTOP,
sellStop = OP_SELLSTOP
};
But if you wanted this to replace actual string literals in your source code, you're going to be disappointed. Either do not use string literals or, if you can't change the input being strings, introduce some mapping using a std::map<std::string, int>.
I have a Mysql table that I am using as a list of different calculations that needs to be done.
Each line in the table has a column of type INT that has the number of the function that needs to be called.
e.g. line 6, data, (function) 1.
I read all the lines one by one and I need to call the relevant functions for each line.
What is the best way to construct it in C++?
should I have another function that returns the pointer of the functions that needs to be called ?
Are there other recommended solutions?
Thanks
It depends on the type of the function (input/outputs) but assuming they are all the same, you can make an array of function pointers. For example:
std::vector<void(*)(int)> MyArray;
Will declare an array of function pointers returning void and taking one int as parameter. Then you can put the functions you want in it and when you want to call them you can use MyArray[i]
If the actual type for the function pointer is long and hard to type, you can use decltype(MyFunction) instead. This requires C++11 though.
Using function pointers may work may work but I would rather make use of something like Strategy pattern.
class DataProcessor {
public:
virtual void process(Data& data) = 0;
// some other things like dtors etc
}
For each type of "function" you can create its corresponding DataProcessor.
To ease lookup, you may make use of a factory, or simply a std::map<int, DataProcessor> (instead of using int as key, will you consider using an enum?), or even a vector/array of DataProcessor.
As a suggestion, this is another way:
//Create only a function and make a switch statement in it:
void myfunction (std::pair<int,int> aRow) { // function:
int result;
int data = aRow.second;
int function_id = aRow.second;
switch(function_id){
case 1:{
//Funcion with any signature
break;
}
case 2:{
//Funcion with another signature
break;
}
//and so on...
}
//do something with the result...
}
int main () {
//Fetch your mysql data here:
std::vector<std::pair<int, int> > myMySQLdata;
for_each (myMySQLdata.begin(), myMySQLdata.end(), myfunction);
}
Suppose I have an enum definition, e.g.:
// myenum.h
enum MyEnum {
First = 1,
Second,
Third,
TwoAgain = Second
};
I would like to programmatically generate a map from any given enum definition, where the key is the enum element's name, and the value is the enum element's numerical value (e.g. myMap["TwoAgain"] == 2)
So far, I know how to traverse the source file using clang_visitChildren(), and extract individual tokens using clang_tokenize(). Recursing through the AST, I get cursors/tokens in this order:
"MyEnum" (CXType_Enum)
"First" (CXToken_Identifier)
"=" (CXToken_Punctuation)
"1" (CXToken_Literal)
"unsigned int" (CXType_UInt)
"1" (CXToken_Literal)
"MyEnum" (CXType_Enum)
"Second" (CXToken_Identifier)
"MyEnum" (CXType_Enum)
"Third" (CXToken_Identifier)
"MyEnum" (CXType_Enum)
"TwoAgain" (CXToken_Identifier)
"=" (CXToken_Punctuation)
"Second" (CXToken_Identifier)
"unsigned int" (CXType_UInt)
"Second" (CXToken_Identifier)
I guess I could write an algorithm that uses this information to calculate every value. However, I was wondering if there's a simpler way? Can I get the numerical values directly from the libclang API?
libclang exposes this information through clang_getEnumConstantDeclValue and clang_getEnumConstantDeclUnsignedValue. A map like you describe can be built by visiting the children of a CXCursor_EnumDecl:
static enum CXChildVisitResult VisitCursor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
if (cursor.kind == CXCursor_EnumConstantDecl) {
CXString spelling = clang_getCursorSpelling(cursor);
myMap[clang_getCString(spelling)] = clang_getEnumConstantDeclValue(cursor);
clang_disposeString(spelling);
}
return CXChildVisit_Continue;
}
As id256 said, I don't think you can do this with libclang. However, Clang's libtooling and plugin interface allow you to access the AST and operate on that directly. For enums, you'll want to look at the EnumDecl class, which allows you to iterate over the inner decls. Then it's just a case of building up a map like:
for (auto declIterator = myEnumDecl.decls_begin();
declIterator != myEnumDecl.decls_end();
++declIterator)
{
myMap[declIterator->getNameAsString()] = declIterator->getInitVal;
}
You can use following way in get name and value for your map. i am using clang 8.
bool VisitEnumDecl(EnumDecl *ED)
{
for (auto it = ED->enumerator_begin(); it != ED->enumerator_end(); it++)
{
std::cout <<it->getNameAsString()<<" "<<it->getInitVal().getSExtValue()<<std::endl;
}
return true;
}
I was wondering if someone out there could give me a pointer to reducing duplication when coding.
im required to call a function a number of times to populate a structure, for example:
typedef struct {
uint16_t u16_a;
bool b_org;
char* c_c;
uint16_t u16_d;
} TEntry;
I need to populate each value of these with a function call, although the return values vary, the same function is used for all.
Would a macro be sufficient to create a template in some way, so that the return type would be dependent on the specific parameter ("string")
for example:
Trrelevant::Trrelevant()
{
TPoint* u_apoint = Insufficient::FindValue("A");
if (u_bpoint != NULL) {
int a = u_apoint;
}
TPoint* p_apoint = Insufficient::FindValue("borg");
if (p_bpoint != NULL) {
bool b = p_bpoint;
}
TPoint* p_cpoint = Insufficient::FindValue("C");
if (etc != NULL) {
char* c = etc;
}
TEct* etc = Insufficient::FindValue("ETC");
if (etc != ETC) {
etc = etc;
}
TEntry entry = {a,
b,
c,
etc};
}
this code is not compiled or accurate, im just trying to illustrate. Im weak in C++ and new to macros, but would anyone know a way to have a macro solve this?
Thank you for your time
You could do something like this, although I don't know what it really buys you.
#define QuickFindValue(NAME, TYPE, FUNCTION) \
TYPE *NAME##Value = Insufficient::FindValue(#NAME); \
if (NAME##Value == NULL) { FUNCTION; }
You would use it like so:
QuickFindValue(C, TPoint, {
char *c = CValue;
// Do stuff..
});
Recently I had the same kind of issue, I'm not sure what kind of source you use for your inputs.
Personnaly, I used XML as input.
Then I have A Builder class that parses the XML call a factory funciton to build every struct in the c++ using the data from the parser.
I don't think that MACRO or templtes would be of any help (or it would be a bad solution).
Note that an external resource (like xml) is nice if ever you want to change without recompiling.
Best
I have a big factory, and I'm trying to figure out how to make it look pretty.
There are about 40 possible object/constructor combinations:
if(algorithm == "SHA-1")
return new HashImpl<...>(algorithm, seed, size);
if(algorithm == "SHA-224")
return new HashImpl<...>(algorithm, seed, size);
if(algorithm == "SHA-256")
return new HashImpl<...>(algorithm, seed, size);
...
if(algorithm == "AES" || algorithm == "AES128")
return new BlockCipherImpl<...>(algorithm, seed, size);
...
if(algorithm == "HmacSHA1")
return new HmacImpl<...>(algorithm, seed, size);
...
Is there a way to put this into a map so I can at least do away with the sequential search? I'm having problems figuring out how to make the constructor a functor.
EDIT: The code can be found here:
http://code.google.com/p/owasp-esapi-cplusplus/source/browse/trunk/src/crypto/SecureRandomImpl.cpp, starting around line 130.
No need to use them fancy newfangled maps.
template <class Impl>
BaseImplementation* makeAlgo (const std::string& algo,
const byte* seed, size_t size)
{
return new Impl(algo, seed, size);
}
typedef BaseImplementation* makeAlgo_t (const std::string& algo,
const byte* seed, size_t size);
typedef struct { std::string name; makeAlgo_t func; } NamedAlgoMaker_t;
NamedAlgoMaker_t factory[] = {
{ "SHA-1", makeAlgo< HashImpl <...> > },
...
{ "HmacSHA1", makeAlgo< HmacImpl <...> > },
...
};
If you keep the array sorted, you can use binary search to find the algorithm quickly.
Of course you can build a map (or hash/unordered map) out of these things too, if you want to.
You can use either a map of lambda functions perhaps
So it will still be visually ugly. But you can make it faster in the following way:
Create ~40 factory methods, each of which returns one of these choices.
Create a map where fnPointerTypedef is the return type of your factory method.
Do a dictionary look up, and return the result of whichever function you look up.
Create an enum that gives a number for each option (e.g. SHA-1 = 0, SHA-224 = 1, etc..).
Create a map that maps the string name to the {int|enum}.
Create an array of function pointers, and have each spot in the array point to the correct corresponding factory method.
Do a dictionary look up and return functionArray[enumInt];
(Edit: Thanks n.m. for more direct implementation)