vector of boost::function not working with _placeholder - c++11

I need your help. I tried a lot to find a solution for the problem but failed so far.
Idea:
Create a vector of "command tuples" like the following:
typedef boost::tuple<std::string, boost::function<void()>> command_tuple;
std::vector<command_tuple> commands {
boost::make_tuple("command1", boost::bind(&myclass::command1, this))
};
If the string "command1" is used the void command1() function is called. The ID index value is based on find_if search for the string ("command1" is ID=0) on the vector.
This is working fine!
boost::get<1>(commands[ID])();
Problem:
I found no way so far to use a vector of boost::function (pointers) defined with any kind type of function parameters:
typedef boost::tuple<std::string, boost::function<void(const char *)>> command_tuple;
std::vector<command_tuple> commands {
boost::make_tuple("command1", boost::bind(&myclass::command1, this, std::placeholders::_1))
};
This will fail with a cannot convert std::_Placeholder<1> to type const char * compilation error.
This is therefore not possible:
boost::get<1>(commands[ID])("dynamic string argument");
Pinning down of the problem:
hmmm ... so I found out so far that even a simple vector of boost::function does not seem to work (in the way I am trying to use it):
std::vector<boost::function<void(const char *)>> commands {
boost::bind(&myclass:command1, this, std::placeholders::_1)
};
Fails with the same compilation error.
It is possible to replace the std::placeholders::_1 with "static string constants" to avoid any compilation errors. But my idea was to use a "dynamic string argument".
Can someone please give me a quick hint of what I am doing wrong or maybe show some simple alternatives. I want to have quite a big list of function pointers that I can call based on their "string name".
I simply want to avoid a big "switch select case" style code block to
select the function to be executed based on a dynamic "input string".
Thanks for your time!

like T.C. replied in the comments. You should never mix std::bind, std::placeholders and boost::bind.

Related

Swift Compiler performance

I got this statement in Swift code which produces an error when executing in playground:
let colors: [String: [Float]] = ["skyBlue" : [240.0/255.0, 248.0/255.0, 255.0/255.0,1.0],
"cWhite" : [250.0/255.0, 250.0/255.0, 250.0/255.0, 1.0]]
The error is : expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
Then I changed the arrays element type to Double which just works fine.
However I am asking myself why this happens ?
As I said using Double it works just fine. So my guess is that Swift tries to guess the type and therefore Double works better in this example than Float.
Similar issues have been reported before, and (as I understand it) the problem is the automatic type inference for "complicated" expressions. You should file a bug report at Apple.
It compiles with a dictionary of one color, but not with two.
In this concrete case, you can work around it by converting each number in the array to a Float explicitly:
let colors = [
"skyBlue" : [Float(240.0/255.0), Float(248.0/255.0), Float(255.0/255.0),Float(1.0)],
"cWhite" : [Float(250.0/255.0), Float(250.0/255.0), Float(250.0/255.0), Float(1.0)]
]

My exists function says the file exists, but winapi functions say it does not

I copied code that's supposed to change desktop wallpaper. I have this constant in my program:
const char * image_name = "button_out.gif";
Later, I write the image on disk using Magick++:
image.write(image_name);
The image appears in program's working directory. If I run the program directly from explorer the working directory equals the program location.
Because the code prints the 0x80070002 - File not found error I added a exist function in the beginning:
#include <sys/stat.h>
bool exists(const char* name) {
struct stat buffer;
return (stat (name, &buffer) == 0);
}
void SetWallpaper(LPCWSTR file){
if(!exists((const char* )file)) {
wcout << "The file "<<file<<" does not exist!" << endl;
return;
... actually try to set a wallpaper ...
}
The error is not printed however and the code proceeds.
Now the question is:
Does my exist function work properly?
Where does windows look for that image?
Full code to set a Magick++ generated image as background in case I have missed something relevant in this question.
Problem 1: String Conversions
Your primary problem is that you are attempting to use LPCWSTR (a const wchar_t *) and const char * interchangeably. I see a number of issues in your source, in particular:
You start with const char * image_name.
You then cast it to a LPCWSTR to pass to SetWallpaper. This basically guarantees that SetWallpaper will fail, as desktop->SetWallpaper is not able to handle non wide-character strings.
You then cast it back to a const char * to pass to stat() via exists(). This should work in your situation (since the original string really is a char *) but isn't correct because your string parameter to SetWallpaper is supposedly a proper LPCWSTR.
You need to pick a string format (wide-character vs. what Windows terms "ANSI") and stick to that format, using consistent APIs throughout.
The easiest option is probably just to leave most of your code untouched, but modify SetWallpaper to take a const char * and convert to a wide-character string when needed (for this you can use mbstowcs). So, for example:
void SetWallpaper(const char * file){ // <- Use a const char* parameter.
...
// Convert to a wide-character string to pass to COM:
wchar_t wcfile[MAX_PATH + 1];
mbstowcs(wcfile, file, sizeof(wcfile) / sizeof(wchar_t));
// Pass the converted wide-character string:
desktop->SetWallpaper(wcfile, 0);
...
}
The other option would be to use wide-character strings throughout, i.e.:
LPCWSTR image_name = L"button_out.gif";
Modify exists() to take a LPCWSTR and use _wstat() instead.
Use wide-character versions of all other API functions.
However, I am unsure how that would interact with the ImageMagick API, which may not have wide-character support. So it's up to you. Choose whatever approach is the easiest to implement but make sure you are consistent. The general rule is do not cast between LPCWSTR and const char *; if you are ever in a situation where you need to change one to the other, you cannot cast, you must convert (via mbstowcs or wcstombs).
Problem 2: SetWallpaper default directory is not current working directory
At this point, your string usage will be consistent. Now that you have that problem ironed out, if SetWallpaper fails while exists() does not, then SetWallpaper is not looking where you think it is. As you discovered in your comment, SetWallpaper looks in the desktop by default. In this case, while I have not tested it, you may be able to work around this by passing an absolute path to SetWallpaper. For this, you can use GetFullPathName to determine the absolute file name given your relative path. Remember to be consistent with your string types, though.
Also, if stat() continues to fail, then that problem is either that your working directory is not what you think it is, or your filename is not what you think it is. To that end you will want to perform the following tests:
Print the current working directory at the point you check for the files existence, verify it is correct.
Print the filename when you check for its existence, verify it is correct.
You should be good to go once you work all the above issues out.

How does a DataObjects::SQLError object's .code correspond to the error issued by the database?

So I'm doing some business logic and want to run some code that goes like
select id from blah where foo = 1234 for update nolock
This code throws a DataMapper::SQLError when the corresponding row in blah is locked. This is desirable behavior; I would like to catch this error and use it to inform my application logic. But I want to re-throw any other SQL errors, because they're different than the case I'm programming for, and catching them in the same way would be wrong.
The error object returned has a string error message, and a numeric code (50463045). It seems like comparing on the numeric code would be great, but I don't want to embed the constant 50463045 in my code without some modicum of understanding of how the heck it was determined. Notably, the Postgres manual suggests that the error code for this state is 55P03, and that doesn't seem to be the same thing. I don't have any idea how much I can trust this magic number, and how to determine it except for experimentally, so I'm not really comfortable with using it.
How is the error code determined?
The Internet was distressingly unhelpful, since searching for stuff about DataObjects SQL errors seems to mostly return problems with other software raising the errors, not information on the errors themselves... but after locating the right source code and browsing around through the source code I finally located do_postgres.c:
void do_postgres_raise_error(VALUE self, PGresult *result, VALUE query) {
const char *message = PQresultErrorMessage(result);
char *sql_state = PQresultErrorField(result, PG_DIAG_SQLSTATE);
int postgres_errno = MAKE_SQLSTATE(sql_state[0], sql_state[1], sql_state[2], sql_state[3], sql_state[4]);
PQclear(result);
data_objects_raise_error(self, do_postgres_errors, postgres_errno, message, query, rb_str_new2(sql_state));
}
Notice how a 5-character state is passed to MAKE_SQLSTATE... and then also passed to data_objects_raise_error itself. I couldn't track down where MAKE_SQLSTATE is defined to figure out what crazy manipulations are going on to make this integer, but it appears I can just use the error object's .sqlstate property directly, and make my condition e.sqlstate == '55P03'.

How to get name of the bit field referenced by BIT_FIELD_REF?

I want to get the name of the field with which it was declared from GENERIC representation. I have a BIT_FIELD_REF tree and it's DECL_NAME is zero. For example,
struct {
int a;
unsigned b:1;
} s;
...
if (s.b)
...
For s.b I'll get a BIT_FIELD_REF and there's no obvious way to get the “b”, which is the original name of the field. How to do it?
Try call debug_c_tree (tree_var) or call debug_tree (tree_var) from GDB, and see if that knows the name. If it does, reverse engineer the pretty-printer.
What exactly did I do: investigating stuff in tree-dump.c I ended up understanding that names of the bit fields where they're known were coming from struct's DIEs and were hard to track.
Then I decided to get the name from the BIT_FIELD_REF argument 0 (reference to structure) type, which is RECORD_TYPE and it stores all the fields' sizes and offsets.
Problem was to understand that BIT_FIELD_REF doesn't reference the bits itself: it is used like BIT_FIELD_REF & INTEGER_CST, where constant acts like mask. After understanding this, I quickly computed the offsets and got the name from the type.

C++: What would be an appropriate solution to forming a collection of different data types?

I'm writing a command line interpreter and I'm trying to setup formats for individual commands. I have things like the name of the command, the maximum amount of parameters and the minimum amount of parameters. I want to have sort of collection, a sort of prototype of what kind of types the parameters are. My first thought was just to declare a vector without the generics, but then I realized this isn't Java.
Let's say I have a command such as "read test.dat 2"
I would want a structure showing that the typical read command has a string and then an integer.
Any ideas?
I'm not really clear about what you are asking so I may be getting this wrong.
From your description ,it sounds as if you have an abstract notion of commands, and that they have names and an expected structure in terms of parameters. From your description, it sounds like you would want a list of type identifiers and indications on whether they are optional.
Then, you could just instantiate a command object for each command you expect to work with, and add all of them to a collection of commands.
Alternatively, use a map collection to map from command names to the actual command objects.
Each command object can also hold a reference to a handler object to actually execute the command.
Heterogenous Container
If you want to have a container that can store a fixed set of types, you can use one of boost::variant:
typedef boost::variant<std::string, int> optval;
typedef std::vector<optval> options;
Now, you can push_back into the vector either strings or integers, and the variant will note what it contains:
options opts;
opts.push_back(10);
opts.push_back("hello");
You can read about it in its documentation at Boost variant, including how to get the right value out of the variant. You can of course also have a map from argument names to such variants, if you have already set up your command line parsing, and don't need libraries for that anymore:
std::map<std::string, optval> map;
map["--max-foo"] = 10;
map["--title"] = "something fun";
Command line parsing
If you want to parse the command line arguments of your program, you can look into the Boost.Program Options library, which will greatly assist you doing that.
Mostly, however, i end up using the posix getopt function, which can also parse the command line. I recommend you to look into boost program options first, and if you feel it's too heavy, you can look into getopt (see man 3 getopt)
Something like this, perhaps:
enum ParameterType
{
Int,
String
};
struct Command
{
string name;
vector<ParameterType> maxParameters;
int minParameters;
};

Resources