question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,276,847 | 1,276,857 | Difference in behavior while using dynamic_cast with reference and pointers | I was checking the behavior of dynamic_cast and found that when it fails, std::bad_cast exception is thrown only if the destination is a reference type. If the destination is a pointer type then no exception is thrown from the cast. This is my sample code:
class A
{
public:
virtual ~A()
{
}
};
class B : public A
{
};
int main()
{
A* p = new A;
//Using reference
try
{
B& b = dynamic_cast<B&>(*p);
}
catch(std::bad_cast exp)
{
std::cout<<"Caught bad cast\n";
}
//Using pointer
try
{
B* pB = dynamic_cast<B*>(p);
if( pB == NULL)
{
std::cout<<"NULL Pointer\n";
}
}
catch(std::bad_cast exp)
{
std::cout<<"Caught bad cast\n";
}
return 0;
}
Output is "Caught bad cast" and "NULL pointer". Code is compiled using VS2008. Is this the correct behavior ? If yes, then why there is a difference?
| Yes, this is correct behaviour. The reason is that you can have a null pointer, but not a null reference - any reference has to be bound to an object.
So when dynamic_cast for a pointer type fails it returns a null pointer and the caller can check for that, but when it fails for a reference type it can't return a null reference, so an exception is the only reasonable way to signal a problem.
|
1,277,512 | 1,277,516 | icon is not in 3.00 format | When building a C++ application in Visual Studio 2008, I receive the following error: iconfile.ico is not in 3.00 format.
I created the icon file using Paint, and saved it as a .ico file.
I tried saving it as 16 bit, 24 bit, and 256 color.
So far, none of these formats appear to be version 3.00.
How do I resolve this?
| I downloaded this:Photo Filtre
I had to convert the file to a .ico file. I had assumed that if I do a "save as", it did more than just change the extension. After the conversion, the icon worked correctly.
|
1,277,600 | 1,277,635 | Install C C++ library under HOME shared via Network File System | My Home directory is shared among several linux computers via Network File System.
I would like to install some C C++ library from source under my Home directory, and wish they can be used under all the linux computers.
Do I have to install different versions of the library under different directories of my Home for different computer?
Assuming I have a C C++ program that calls these libraries, how do I specify different include and link files and directories for different computer in Makefile? Is it to determine the directories based on the hostname of the computer?
Is it possible to combine the different versions of the .a and .so files and header files of the libary for different linux computers so that the include and link files and directories of the libary are the same for all the computers and I don't have to specify different directories for different computer in the Makefile of my C C++ program?
Thanks and regards!
| This is easy and common.
By C C++ I assume you mean you have libraries compiled with a C compiler, and those compiled with a C++ compiler.
If the version of the compiler you are using is the same, then you do not need different libraries for each version. If they are different it may still be possible to use the same C libraries, but C++ becomes more problematic.
If the files are in your home directory, the easiest thing to do in your Makefile is make all of the paths relative to $HOME. This environment variable should be set correctly on each system.
If you need to reference different libraries on the different machines, the most straightforward way would be to put them in a directory with the same name as the hostname. Something like this:
CXXFLAGS=-I$(HOME)/app/$(HOST)/include
You could do something more fancy by extracting the gcc version number and using that, but its probably overkill for just a couple of machines.
|
1,277,650 | 1,277,717 | Templatized Virtual function | We know that C++ doesn't allow templated virtual function in a class. Anyone understands why such restriction?
| Short answer: Virtual functions are about not knowing who called whom until at run-time, when a function is picked from an already compiled set of candidate functions. Function templates, OTOH, are about creating an arbitrary number of different functions (using types which might not even have been known when the callee was written) at compile-time from the callers' sides. That just doesn't match.
Somewhat longer answer: Virtual functions are implemented using an additional indirection (the Programmer's General All-Purpose Cure), usually implemented as a table of function pointers (the so-called virtual function table, often abbreviated "vtable"). If you're calling a virtual function, the run-time system will pick the right function from the table. If there were virtual function templates, the run-time system would have to find the address of an already compiled template instance with the exact template parameters. Since the class' designer cannot provide an arbitrary number of function template instances created from an unlimited set of possible arguments, this cannot work.
|
1,277,685 | 1,278,209 | organize project and specify directory for object files in Makefile | Here are my two questions:
I am now learning to manage my code with CVS, and I just want to make a repository for my C++ files, Makefile and bash and python scripts only, not the object files and executables. So I made several subdirectories under my project directory: src, bin, scripts, results and data.
I put C++ files and Makefile under ~/myproject/src, Bash and Python scripts under ~/myproject/scripts and object and executables under ~/myproject/bin. I am hoping only the files under src and scripts will be updated via CVS. I wonder how you organize your projects? Just hope to follow some good habits.
Since I put my C++ files and Makefile into ~/myproject/src and object and executable files into ~/myproject/bin, I have to specify the directories in Makefile. Here is what I am doing
Makefile:
...
BIN_DIR=/home/myproject/bin/
all: $(BIN_DIR)myexecutable TAGS
TAGS: *.cc *.h
etags --members --declarations -l c++ *.cc *.h
$(BIN_DIR)myexecutable: $(BIN_DIR)myobject.o
$(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS)
Makefile.depend: *.h *.cc Makefile
$(CXX) -M $(CXXFLAGS) *.cc > Makefile.depend
clean:
\rm -f $(BIN_DIR)myexecutable $(BIN_DIR)*.o Makefile.depend TAGS`
However this will give error
make: *** No rule to make target /home/myproject/bin/myobject.o', needed by /home/myproject/bin/myexecutable'.
How to specify a different directory for object and executable files from C++ files in Makefile?
|
You can keep your files in different directories if you like, but that isn't necessary. Add a file or directory to the CVS repository once, and CVS will retain it indefinitely. From then on you can update it, check it in, whatever. If you don't add an object file to the repository, CVS won't touch it. If you want to add a whole directory tree, and you're in the habit of keeping objects there, just make clean before you do it.
Make is a wonderful tool, but it has some glaring faults. What you're describing is one of the classic problems: Make is good at using a source there to make something here, but not the other way around. Here are a couple of ways to do what you're trying to do.
A) Run make in your binary directory:
...
all: myexecutable TAGS
myexecutable: myobject.o
$(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS)
VPATH = /home/myproject/src
...
cd ~/myproject/bin
make -f ../src/makefile
B) Put the objects on the bin directory by brute force:
$(BIN_DIR)%.o: %.cc
$(CXX) $(CXXFLAGS) -c -o $@ $^
This will give you a problem with Makefile.depend, which you can approach several ways.
C) Learn some more advanced Make techniques. You probably shouldn't try this yet.
|
1,277,917 | 1,277,948 | win32 : Get the state of an event object | I'm creating 3 events with the following function:
HANDLE WINAPI CreateEvent(...);
I'm waiting on all (bWaitAll is set to TRUE) event objects or a timeout with:
DWORD WINAPI WaitForMultipleObjects(...);
The return value is:
WAIT_TIMEOUT
Is there an easy way to check each event to find the one(s) that was(where) not set?
As an example :
HANDLE evt1 = ....
HANDLE evt2 = ....
HANDLE evt3 = ....
HANDLE evts[3] = ....
DWORD ret = ::WaitForMultipleObjects(3, evts, TRUE, 10000);
After 10 sec :
'ret' is WAIT_TIMEOUT.
evt1 is set
evt2 is NOT set
evt3 is set
The return value tells me "The time-out interval elapsed and the conditions specified by the bWaitAll parameter are not satisfied.", but not which one were signaled and which one were not.
Thanks,
| Yes, after WaitForMultipleObjects() returned call WaitForSingleObject() for each event specifying zero timeout.
It will return WAIT_TIMEOUT for events that are not signalled and WAIT_OBJECT_0 for signalled events. Don't forget to check for WAIT_FAILED.
Surely each event state might have been changed compared to the states they had at the moment WaitFormultipleObjects() returned.
|
1,278,158 | 1,278,448 | What is the difference between Boost::bind and Boost Phoenix::bind? | What is the difference between Boost::bind and Boost Phoenix::bind?
| phoenix::bind is like lambda::bind a function that returns an expression template that records that it has to call the given function. These are designed to work together with phoenix and lambda, respectively. As a result, they contain much more things. Like, the type they return overloads all possible operators so that their respective action can be recorded and executed later.
boost::bind is "just" a binder. It will bind the function, and return a type that has the function call operator overloaded, and not much more.
|
1,278,259 | 1,278,362 | C++ fstream << and >> operators with binary data | I've always read and been told that when dealing with binary files that one should use read() and write() as opposed to the << and >> operators as they are meant for use with formatted data. I've also read that it is possible to use them, but it is an advanced topic, which I can't find where anyone dives into and discusses.
I recently saw some code which did the following:
std::ifstream file1("x", ios_base::in | ios_base::binary);
std::ofstream file2("y", ios_base::app | ios_base::binary);
file1 << file2.rdbuf();
When I pointed out the use of the << operator with the binary file, I was told that the rdbuf() call returns a streambuf * and that << overloads the streambuf* and does a direct copy with no formatting and is thus safe.
Is this true and also safe? How about efficiency? Any gotchas? Details would be much appreciated.
Thanks!
| Yes (see 27.6.2.5.3/6 where the overload of << for streambuf is described).
|
1,278,294 | 1,278,352 | Winpcap simple question - how to send packets to a specified ip/port? | I read the tutorials and so, but I am not getting it. It does let you send packets, but how can you tell Winpcap where to send those packets? Is there any header I should put on the packets so it will know to which ip/port's to forward it? I mean. Let's imagine I want to send some data to my MSN, as if I had wrote something to someone on my list. I can use the sendpacket(), but it will only take the packet/byte array as argument, not specifing to which app/ip/port so send it.
Thanks
| You don't tell Winpcap where to send packets. You tell it to put a packet on the wire. The network switch will send the packet to the right destination. The TCP stack on the receiving end will send the packet to the right application/service. Obviously this means the routing information has to be in the packet itself.
To take your example, you'd need to put the IP address and TCP port of the appropriate MSN server in the packet. If you don't, your networking hardware will discard or misroute that packet.
|
1,278,445 | 1,278,487 | Boost::bind and std::copy | I'm trying to use Boost::bind and std::copy to print out the values in a list of lists. Obviously, I could use loops, and I may end up doing so for clarity, but I'd still like to know what I'm doing wrong here.
Here is the distilled version of my code:
#include <boost/bind.hpp>
#include <iterator>
#include <algorithm>
#include <list>
#include <iostream>
using namespace std;
using namespace boost;
int main(int argc, char **argv){
list<int> a;
a.push_back(1);
list< list<int> > a_list;
a_list.push_back(a);
ostream_iterator<int> int_output(cout,"\n");
for_each(a_list.begin(),a_list.end(),
bind(copy,
bind<list<int>::iterator>(&list<int>::begin,_1),
bind<list<int>::iterator>(&list<int>::end,_1),
ref(int_output)
) //compiler error at this line
);
return 0;
}
The compiler error starts off
error: no matching function call to bind(<unresolved overloaded function type> .....
I think this means that bind can't figure out what the return type for the outermost bind should be. I don't blame it, because I can't either. Any ideas?
| The template arguments to std::copy cannot deduced in the context of the bind call. You need to specify them explicitly:
copy< list<int>::iterator, ostream_iterator<int> >
Also when you write:
for_each(a_list.begin().a_list.end(),
I think that you mean:
for_each(a_list.begin(),a_list.end(),
And you're missing #include <iostream> for definition of std::cout.
|
1,279,094 | 1,279,400 | Error on boost phoenix::bind compiling | I'm using phoenix::bind and receiving this error message:
error C2039: 'bind' : is not a member
of 'phoenix'
The code line where I'm using bind and where the error is pointing is:
phoenix::bind(
&OptionalInputPort::eraseDataEditor )
( phoenix::var( *optionalPort ) )
and I can't figure out what is the problem.
the phoenix include is this line: #include boost/spirit/home/phoenix.hpp
Thanks.
| The phoenix namespace is inside the boost namespace (just like everything else in Boost).
boost::phoenix::bind( &OptionalInputPort::eraseDataEditor ) ( boost::phoenix::var( *optionalPort ) )
To avoid all that typing, you could preface your C++ file with this to create a namespace alias:
namespace phoenix = boost::phoenix;
Then your original code should work. If you're using bind a lot, you could tell your compiler that when you say bind, you mean the one in boost::phoenix:
using boost::phoenix::bind;
If you're using lots of stuff from Phoenix, you could just bring in everything from that namespace, although that can have unintended consequences since it will include the stuff that you didn't even know existed, and that could interfere with your own code.
using namespace boost::phoenix;
|
1,279,177 | 1,279,202 | c++ fread changing fgetpos strangely | If I run:
FILE* pFile = fopen("c:\\08.bin", "r");
fpos_t pos;
char buf[5000];
int ret = fread(&buf, 1, 9, pFile);
fgetpos(pFile, &pos);
I get ret = 9 and pos = 9.
However if I run
FILE* pFile = fopen("c:\\08.bin", "r");
fpos_t pos;
char buf[5000];
int ret = fread(&buf, 1, 10, pFile);
fgetpos(pFile, &pos);
ret = 10 as expected, but pos = 11!
How can this be?
| You need to open the file in binary mode:
FILE * pFile = fopen("c:\\08.bin", "rb");
The difference is cause by reading a character that the library thinks is a newline and expanding it - binary mode prevents the expansion.
|
1,279,290 | 1,280,318 | Overhead of C++ inheritance with no virtual functions | In C++, what's the overhead (memory/cpu) associated with inheriting a base class that has no virtual functions? Is it as good as a straight up copy+paste of class members?
class a
{
public:
void get();
protected:
int _px;
}
class b : public a
{
}
compared with
class a
{
public:
void get();
protected:
int _px;
}
class b
{
public:
void get();
protected:
int _px;
}
| There might a be slight memory overhead (due to padding) when using inheritance compared to copy and past, consider the following class definitions:
struct A
{
int i;
char c1;
};
struct B1 : A
{
char c2;
};
struct B2
{
int i;
char c1;
char c2;
};
sizeof(B1) will probably be 12, whereas sizeof(B2) might just be 8. This is because the base class A gets padded separately to 8 bytes and then B1 gets padded again to 12 bytes.
|
1,279,292 | 1,279,398 | How do I create a Win32 DLL without a dependency on the C runtime | Using Visual Studio 2008 and its C/C++ compiler, how do I create a Win32 DLL that is dependent only on other Windows DLLs, and has no dependency on the Microsoft C runtime?
I have some C code I want to place in a DLL that is entirely computation, and makes almost no use of C library functions.
For those it does use (eg memcpy), I'm happy to rework the code to use the Win32 API equivalents (eg CopyMemory).
| Use the /NODEFAULTLIB linker option and (of course) make sure you have no actual dependencies on the runtime. You'll also have to specify & define your own entry point for the DLL using the /ENTRY linker option or alternatively have your own entry point function that matches the name expected by the compiler/linker (for a dll, that's _DllMainCRTStartup).
Matt Pietrek's article from way back when on LIBCTINY will probably have all the information you need:
http://msdn.microsoft.com/en-us/library/bb985746.aspx
|
1,279,564 | 1,389,644 | Compiliation errors on boost files | I'm getting a lot of errors compiling code using the boost libraries, mainly when I'm using Spirit namespace. The errors are syntax errors on boost files like:
boost/spirit/home/classic/dynamic/lazy.hpp(33) : error C2143: syntax error : missing ';' before '<'
or
boost/spirit/home/classic/dynamic/lazy.hpp(33) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
or
boost/spirit/home/classic/utility/grammar_def.hpp(104)
: error C2039: 'nil_t' : is not a
member of 'boost::phoenix'
I am migrating from Visual Studio 6 to Visual Studio 2008 Express and from one of the oldest versions of boost to the lastest.
I'd like to know what's the problem. I'm thinking the problem can't be in the boost library.
| The problem was resolved just including phoenix1 the old version of phoenix.
|
1,279,592 | 1,280,974 | Serial programming (hardware handshake) | I'm trying to to program a serial communication using hardware handshake in linux using C/C++. The signals that implement the handshake are CTS (Clear to send) and RTS (Request to send). Currently my function for setting the CTS signal looks as follows:
int setCTS(int fd, int value) {
int status;
ioctl(fd, TIOCMGET, &status); // get the current port status
if (value)
status |= TIOCM_CTS; // rise the CTS bit
else
status &= ~TIOCM_CTS; // drop the CTS bit
ioctl(fd, TIOCMSET, $status); // set the modified status
return 0;
}
where fd is the file descriptor for the port and value is the value to be set for the signal. To code this function I based on http://www.easysw.com/~mike/serial/serial.html#5_1.
The problem is that gcc does not recognize any of the constants used in the example. Any suggestions?
-- Update --
I've found an answer. Looking to another example, sys/ioctl.h declares the constants.
| This may not be applicable for your particular application, but I thought I'd post it here in case it helps you or someone else searching.
On most systems with termios, you can set the CRTSCTS flag in the ->c_cflags member of the termios structure that you pass to tcsetattr, and have the kernel or hardware do the RTS/CTS flow control for you.
(It's not POSIX, but it's on both BSD and SystemV derived systems so it's almost everywhere - including Linux).
|
1,279,634 | 1,279,695 | C++ Callbacks using Boost Functions and C++ Class Methods | Is there a non-hacky (i.e. no assembly, ...) way to use boost functions to create callbacks with non-static class methods?
Currently for static methods:
list<function<void (LuaState&)> > _callbacks;
I was thinking something along the lines of
list<tuple<function<void (void *, LuaState&)>, void*> _callbacks;
but boost functions doesn't like those void*s.
| function<void (LuaState&)> on_whatever
= bind(&my_class::my_method, &my_object_of_type_my_class, _1);
|
1,279,646 | 1,279,658 | C++ Code not building with build project (F6) in Visual Studio 2008 | I have a large solution that contains C# and C++ projects. After I code in my classes or functions I run a build to have the parser check syntax. What I have noticed is that when I press F6 the entire solution will build and get parsed except for the C++ files that I'm working on.
This seems like it's not the intended function of the editor so is there a way I can force this to happen when I perform a build?
Thanks,
P.S. I know I can go to rebuild project and force a build that way. I'm looking for a way to have the editors treatment of C++ and C# files be consistent.
| In the solution properties, under "Configuration Properties", make sure the C++ projects are set to build. Also, make sure the project dependencies are setup properly.
These two things control which projects are built when you run a build.
|
1,279,653 | 1,279,720 | why I can't use normal C++ classes with Qt | Can anyone pls tell me that, why I can't use normal C++ classes within a Qt programme. If there is any class which aren't inherited from QObject the compiler give me a linking error called,
error LNK2019: unresolved external symbol _main referenced in function _WinMain@16
I'm using Qt 4.5.2 (compiled by myself) with vs2005. Pls help me to solve this !
Edit:
Example...
//UnitManager.h
class UnitManager
{
public:
//-Some code
};
//CivilizationViewer.h
class CivilizationViewer : public QMainWindow
{
Q_OBJECT
//-some code
};
//main
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CivilizationViewer w;
w.show();
return a.exec();
}
If I include UnitManager.h in CivilizationViewer.h compiler will give me that error. (eventhough I include UnitManager.h in main.cpp compiler will give me the error)
| The error you gave doesn't have anything to do with what classes you're using. It looks like it's related to the entry point you have set for your application. Usually you want to use main() instead of WinMain() in Qt programs. Make sure your configuration is set up right.
You included a little bit of code in your question. Is that everything? If so, you're missing a main function.
|
1,280,009 | 1,280,037 | What is the complexity of hash_set::size() in C++ STL? | That is, the computational complexity. Does it have to count all the elements? Does it depend on implementation? The SGI spec doesn't guarantee anything.
| The current C++ standard doesn't specify a hash_set, so yes,
it is implementation dependent. I find it a bit hard to imagine an
acceptable implementation for which this wouldn't be
constant time, however.
|
1,280,178 | 1,280,365 | Methods defined outside class? | I am wondering if php methods are ever defined outside of the class body as they are often done in C++. I realise this question is the same as Defining class methods in PHP . But I believe his original question had 'declare' instead of 'define' so all the answers seem a bit inappropriate.
Update:
Probably my idea of define and declare were flawed. But by define outside of the class body, i meant something equivalent to the C++
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
All the examples of php code have the the code inside the class body like a C++ inlined function. Even if there would be no functional difference between the two in PHP, its just a question of style.
| Having the declaration of methods in header files separate from their implementation is, to my knowledge, pretty unique to C/C++. All other languages I know don't have it at all, or only in limited form (such as interfaces in Java and C#)
|
1,280,304 | 1,280,362 | Why is *= different regarding loss of data on conversion? | I have the following example, compiled in VS2005, warning level 4:
int main(int argc, char *argv[])
{
short s = 2;
short t = 3;
t *= s; // warning C4244: '*=' : conversion from 'int' to 'short', possible loss of data
t = t * s;
}
It doesn't seem to me there should be a warning on either line.
Does *= create an implicit conversion to int for some reason?
EDIT:
Seems like the lack of warning on the second line (and in VS2008) are the real questions.
Thanks for the answers.
| Yes. All arithmetic operators in C++ are defined on int and wider. When you multiply two shorts (doesn't matter if you use * or *=) they are both converted to int first. This is covered by ISO C++ 5[expr]/9:
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:
If either operand is of type long double, the other shall be converted to long double.
Otherwise, if either operand is double, the other shall be converted to double.
Otherwise, if either operand is float, the other shall be converted to float.
Otherwise, the integral promotions (4.5) shall be performed on both operands.
Then, if either operand is unsigned long the other shall be converted to unsigned long.
Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.
Otherwise, if either operand is long, the other shall be converted to long.
Otherwise, if either operand is unsigned, the other shall be converted to unsigned.
[Note: otherwise, the only remaining case is that both operands are int]
and 4.5[conv.prom]:
1 An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.
2 An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) can be converted to an rvalue of the first of the following types that can represent all the values of its underlying type: int, unsigned int, long, or unsigned long.
3 An rvalue for an integral bit-field (9.6) can be converted to an rvalue of type int if int can represent all the values of the bit-field; otherwise, it can be converted to unsigned int if unsigned int can represent all the values of the bit-field. If the bit-field is larger yet, no integral promotion applies to it. If the bit-field has an enumerated type, it is treated as any other value of that type for promotion purposes.
4 An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.
5 These conversions are called integral promotions.
Why it only gives a warning on one line but not both is unclear, however.
|
1,280,586 | 1,280,611 | Hunt the Wumpus - Room Connection | So I'm writing a version of the game Hunt the Wumpus in C++. The only real difference is that I'm not worried about the cave having a dodecahedron shape.
So far I've implemented the creation of the cave and the random insertion of the hero, bat, wumpus, and pit.
// Hunt the Wumpus
#include "std_lib_facilities.h"
#include "time.h"
class Room{
bool is_occupied;
bool has_wumpus;
bool has_bat;
bool has_pit;
public:
Room() // default constructor
{
is_occupied = false;
has_wumpus = false;
has_bat = false;
has_pit = false;
}
void random_insert(vector<Room>& v);
};
void Room::random_insert(vector<Room>& v)
{
srand(time(NULL));
int random_room = 0;
bool crowded = true;
random_room = rand() % 20; // insert hero
v[random_room].is_occupied = true;
while(crowded) // insert...THE WUMPUS!
{
random_room = rand() % 20;
if(v[random_room].is_occupied) ;
else if(!v[random_room].is_occupied)
{
v[random_room].has_wumpus = true;
crowded = false;
}
}
crowded = true;
while(crowded) // insert bat
{
random_room = rand() % 20;
if(v[random_room].is_occupied || v[random_room].has_wumpus) ;
else if(!v[random_room].is_occupied && !v[random_room].has_wumpus)
{
v[random_room].has_bat = true;
crowded = false;
}
}
crowded = true;
while(crowded) // insert pit
{
random_room = rand() % 20;
if(v[random_room].is_occupied || v[random_room].has_wumpus || v[random_room].has_bat) ;
else if(!v[random_room].is_occupied && !v[random_room].has_wumpus && !v[random_room].has_bat)
{
v[random_room].has_pit = true;
crowded = false;
}
}
}
vector<Room> create(Room& r)
{
vector<Room> c;
for(int i = 0; i < 20; ++i)
c.push_back(r);
return c;
}
int main()
{
Room r;
vector<Room> cave = create(r); // create cave
r.random_insert(cave); // randomly insert things
}
I've got a good idea of how I'm going to implement everything else with bats dropping the hero into random places, shooting, outputting current situation, etc.
However, I'm not sure how to deal with randomly connecting the rooms in the cave. I've considered doing some kind of random sort in the vector and then connecting the rooms to the left and right with pointers, but that is just a long hallway, not a cave. Maybe I could create some kind of coordinates system? Does anyone have any recommendations? Thanks.
| A simple solution is to pick a room with less than 3 exits, and connect to it to a random room (watch out for double connections of course). Once there are no rooms with less than 3 exits, terminate. With only 20 or so rooms it doesn't really matter how slow your implementation is.
Edit: There's a chance that some part of the map will be "cut off" from the rest this way, or connected only by one corridor. It may help to start off with a "long hallway" and then apply the above algorithm, to be sure this can't occur.
|
1,280,885 | 1,280,890 | Safely overloading stream operator>> | There's a ton of information available on overloading operator<< to mimic a toString()-style method that converts a complex object to a string. I'm interested in also implementing the inverse, operator>> to deserialize a string into an object.
By inspecting the STL source, I've gathered that:
istream &operator>>(istream &, Object &);
would be the correct function signature for deserializing an object of type Object. Unfortunately, I have been at a loss for how to properly implement this - specifically how to handle errors:
How to indicate invalid data in the stream? Throw an exception?
What state should the stream be in if there is malformed data in the stream?
Should any flags be reset before returning the reference for operator chaining?
|
How to indicate invalid data in the stream? Throw an exception?
You should set the fail bit. If the user of the stream wants exception to be thrown, he can configure the stream (using istream::exceptions), and the stream will throw accordingly. I would do it like this, then
stream.setstate(ios_base::failbit);
What state should the stream be in if there is malformed data in the stream?
For malformed data that doesn't fit the format you want to read, you usually should set the fail bit. For internal stream specific errors, the bad bit is used (such as, if there is no buffer connected to the stream).
Should any flags be reset before returning the reference for operator chaining?
I haven't heard of such a thing.
For checking whether the stream is in a good state, you can use the istream::sentry class. Create an object of it, passing the stream and true (to tell it not to skip whitespace immediately). The sentry will evaluate to false if the eof, fail or bad bit is set.
istream::sentry s(stream, true);
if(!s) return stream;
// now, go on extracting data...
|
1,281,329 | 1,281,357 | Using an Objective-C++ file from a C++ file | I have a c++ app that I'm trying to port to iPhone and to start off I'm trying to replace my c++ texture loader with an obj-c++ texture loader so that I can make use of the cocoa libraries.
A lot of my c++ files (.cpp files) call the texture loader with something like:
GLuint mTexture = TextureLoader::LoadTexture("file.png") //LoadTexture is a static method`
but whenever I try to make a TextureLoader class (inside a .mm file) that has Obj-C code, I am forced to make the calling class also a .mm file.
I want to avoid a creep of .mm usage. How can I do it? Is it even possible?
Basically I have a .mm file that has...
GLuint TextureLoader::LoadTexture(const char* path)
{
//...lots of c and obj-c code
return texture
}
and is apart of a c++ class (or is it obj-c++ at this point?)
I want to be able to use it from a .cpp file without having to make the calling class also .mm
Is there anyway to do this?
Cheers guys.
| I'm not aware of any way to do that. However, you are not required to put all C++ member function definitions in a single file - just stick all the pure C++ stuff into .cpp, and those that need ObjC into .mm.
As well, if you actually have the same repeated ObjC code (perhaps parametrized), then refactor it into a plain C function or C++ class in one separate .mm - such that there are no ObjC constructs in the corresponding .h - and then use that function/class where needed by including the header.
|
1,281,415 | 2,340,728 | error C2719: '_Val': formal parameter with __declspec(align('16')) won't be aligned? | I'm trying to create a vector for D3DXMATRIXA16 like so: vector<D3DXMATRIXA16> matrices; and am getting the error:
d:\Program Files\Microsoft Visual Studio 9.0\VC\include\vector(717) :
error C2719: '_Val': formal parameter
with __declspec(align('16')) won't be
aligned
e:\projects\emuntitled\em\emscratch\emshadow.h(60) :
:see reference to class template
instantiation 'std::vector<_Ty>' being
compiled
with
[
_Ty=D3DXMATRIXA16
]
Why is that exactly?
Thanks for any help!
| It is a known issue [link dead] that stl::vector cannot properly contain aligned data, such as D3DXMATRIXA16. One poster pinned the root cause (or at least, one of them?): the declaration of vector::resize passes the aligned data by value, and not as const reference.
Several workarounds were suggested in that thread, the safest being dropping stl::vector altogether. You might also want to fix the stl headers yourself and recompile - this actually may be easier than it sounds, but I haven't done so myself.
EDIT: links are now broken (thanks @David Menard), here's an alternative, more elaborate answer.
The issue is fixed in VS2012RC - here's a link to a corresponding connect issue [link dead]. Turns out it was actually an issue in the C++ standard itself, fixed in 2008.
|
1,281,608 | 1,281,688 | How do you set icons of .exe files? | Preferably using C++. Or a tool I can use from the command line. So far I've figured out how to extract icons from .exe files, but I can't set icons... Any suggestions?
| Here's a code sample that might help:
Change Icon of EXE file through code extracting it from other EXE file
|
1,281,641 | 1,281,671 | Circular C++ Header Includes | In a project I have 2 classes:
// mainw.h
#include "IFr.h"
...
class mainw
{
public:
static IFr ifr;
static CSize=100;
...
};
// IFr.h
#include "mainw.h"
...
class IFr
{
public float[mainw::CSize];
};
But I cannot compile this code, getting an error at the static IFr ifr; line. Is this kind of cross-inclusion prohibited?
|
Is this kind of cross-inclusions are prohibited?
Yes.
A work-around would be to say that the ifr member of mainw is a reference or a pointer, so that a forward-declaration will do instead of including the full declaration, like:
//#include "IFr.h" //not this
class IFr; //this instead
...
class mainw
{
public:
static IFr* ifr; //pointer; don't forget to initialize this in mainw.cpp!
static CSize=100;
...
}
Alternatively, define the CSize value in a separate header file (so that Ifr.h can include this other header file instead of including mainw.h).
|
1,281,733 | 1,281,760 | QThread Not Starting | I try to create a thread in QT, can declare, create and start it, however it doesn't fire Run function (I can see that via putting a breakpoint in that function)
VT.h:
class VT : public QThread
{
public:
void Run();
};
VT.cpp
void VT::Run()
{
..
}
and in main.cpp:
VT vt;
vt.Start();
// starts ok but no action
I am including other headers in VT.h, do they block? With some incomp. issue?
| Your Run function started with a capital R, QThread's virtual run() is lower-case. The compiler thinks your Run() is something totally unrelated to QThread.
Try renaming your function to void VT::run().
Also, it's a good idea to make your run function protected, just like in QThread.
|
1,281,879 | 1,281,894 | What high level languages are easily interfaced with C / C++? | I have experience with OCaml. You had to write a stub for every function you wanted to use to convert the types even C int <-> OCaml int.
Linking was painful a well.
I don't even want to thing about mapping C++ objects.
What about other popular languages? Is it always a pain?
EDIT:
Please avoid duplicates. And state C and C++ interfacing capabilities separately.
EDIT 2:
Please be specific. "X can call C" doesn't give too much information.
| Nearly all of the scripting languages (Perl, Python, Lua, PHP, Ruby, Tcl) are intended to be embedded into C and C++.
A good survey paper of the relative merits of the APIs:
H. Muhammad and R. Ierusalimschy. C APIs in extension
and extensible languages. Journal of Universal Computer
Science, 13(6):839–853, 2007.
See also this very similar question (and my answer in particular ;)).
|
1,281,930 | 1,286,832 | How to use WndProc from a C++ dll? | I want to handle some SAPI messages from a DLL, which is some sort of plugin. How to handle messages/events inside a VC++ dll. The SAPI event handling is shown in the example at:
http://msdn.microsoft.com/en-us/library/ms720165%28VS.85%29.aspx
| To process "normal" messages, you still need a Window object. It can be a special "message-only" window that only shares the messaging queue infrastructure with normal windows. To create it, first register your message handling class with RegisterClass(). Next, create an message queue by passing HWND_MESSAGE as the parent window to CreateWindow(). You will get back an HWND you can then to SAPI.
However, SAPI supports other interfaces as well. The ISpNotifySource documentation names 4: Windows messages, callbacks, events and COM (ISpNotifySink). To use callbacks, simply pass the address of one of your DLL methods to SetNotifyCallbackFunction.
|
1,282,177 | 1,282,189 | Inferring the return type of a function or functor in C++ | I need to use a function's/functor's returned value without knowing what type it is (that is, as a template).
While I could pass it over to a second function without a problem:
template <typename T>
void DoSomething(T value);
...
DoSomething(FunctionWhoseReturnedTypeIsUnknown(...));
I want to use the returned value inline (without the need to call a second function):
WhatGoesHere? x=FunctionWhoseReturnedTypeIsUnknown(...);
The two methods seem conceptually identical to me (generic-programming-wize), but can the latter be achived in C++?
| Not yet. In C++0X you'll be able to use auto as WhatGoesHere. There is already experimental support for this in some compilers (gcc 4.4 for instance).
|
1,282,212 | 1,282,273 | Global structs not being seen | Defined as: Class.h
#ifndef CLASS_H_
#define CLASS_H_
#include "Class2.h"
#include <iostream>
struct Struct1{
};
struct Struct2{
};
class Class1 {
};
#endif
Then the other header file, where I use this:
#ifndef CLASS2_H_
#define CLASS2_H_
#include "Class.h"
class Class2 {
public:
Class2( Struct1* theStruct, Struct2* theStruct2); //Can't find struct definitions
private:
};
#endif
These are in the same directory. And it isn't seeing those struct definitions! They look to be in global scope to me. Can someone explain to me why Class2 can't see them? The compiler isn't complaining about not finding the header of Class, so it can't be that.
| What follows is a guess at your complete code. Please post that, then we can help you better.
If by any chance your complete code looks like the following then you should change it
#ifndef CLASS_H_
#define CLASS_H_
#include <iostream>
#include "Class2.h"
struct Struct1{
};
struct Struct2{
};
class Class1 {
};
#endif
Because the CLASS_H_ macro will already be defined, in Class2.h the other header won't be included another time, and then at that time Struct1 and Struct2 would not be known yet. Fix it by using a forward declaration where possible. For example in Class2.h:
#ifndef CLASS2_H_
#define CLASS2_H_
// no need for that file
// #include "Class.h"
// forward-declarations suffice
struct Struct1;
struct Struct2;
class Class2 {
public:
Class2( Struct1 theStruct, Struct2 theStruct2);
private:
};
#endif
If the other header doesn't need the definition of Class2 either, then use a forward declaration too, there. The definition is not needed for (i.e a declaration suffices)
References and Pointers
Function parameters in function declarations that aren't definitions
It's needed if you want to access a member, want to get the sizeof or want to defined a function that has a parameter type of Class2, Struct1 etc by-value.
|
1,282,213 | 1,282,224 | Working out address alignment | How do you work out the alignment of an address by just looking at it?
On a 32bit system, an address of 0x12345670 means it's 16 byte aligned (because of the 0 on the end) right?
So what about:
0x12345671
0x12345672
0x12345673
etc?
Cheers,
Jon
| An address A is n-aligned if A mod n is 0. So 0x12345671 and 0x12345673 are 1 aligned, and 0x12345672 is 2-aligned. 0x12345670 is, simultaneously, 1-aligned, 2-aligned, 4-aligned, 8-aligned, and 16-aligned. You only mention the highest power of two (as the lower powers are implied).
|
1,282,295 | 1,282,345 | What exactly is nullptr? | We now have C++11 with many new features. An interesting and confusing one (at least for me) is the new nullptr.
Well, no need anymore for the nasty macro NULL.
int* x = nullptr;
myclass* obj = nullptr;
Still, I am not getting how nullptr works. For example, Wikipedia article says:
C++11 corrects this by introducing a new keyword to serve as a distinguished null pointer constant: nullptr. It is of type nullptr_t, which is implicitly convertible and comparable to any pointer type or pointer-to-member type. It is not implicitly convertible or comparable to integral types, except for bool.
How is it a keyword and an instance of a type?
Also, do you have another example (beside the Wikipedia one) where nullptr is superior to good old 0?
|
How is it a keyword and an instance of a type?
This isn't surprising. Both true and false are keywords and as literals they have a type ( bool ). nullptr is a pointer literal of type std::nullptr_t, and it's a prvalue (you cannot take the address of it using &).
4.10 about pointer conversion says that a prvalue of type std::nullptr_t is a null pointer constant, and that an integral null pointer constant can be converted to std::nullptr_t. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passing nullptr to select the pointer version. Passing NULL or 0 would confusingly select the int version.
A cast of nullptr_t to an integral type needs a reinterpret_cast, and has the same semantics as a cast of (void*)0 to an integral type (mapping implementation defined). A reinterpret_cast cannot convert nullptr_t to any pointer type. Rely on the implicit conversion if possible or use static_cast.
The Standard requires that sizeof(nullptr_t) be sizeof(void*).
|
1,282,357 | 1,282,374 | Broadcast server presence over network | I'm writing a client-server application where client should be able to automatically detect server presence in the network so that user would not have to mess with manual configuration.
I think that server should broadcast its presence somehow. What is the best way to do it?
Server is to be run on either Windows / Linux or OS X, so the solution should be cross-platform. Client and server are written in C++.
| You should look into ZeroConf as a generic way of broadcasting this information. It's also known as Bonjour (formerly Rendezvous) on Apple systems, but it's not an Apple-specific thing - plenty of other devices (both embedded and OSs) broadcast/use it.
There are plenty of libraries that can deal with ZeroConf in plenty of languages - finding one is a matter of Googling it. Bear in mind that ZeroConf itself is the advertising/discovery part of the process and identifies a machine and a socket - but you can then do whatever you want over the socket(s) that you identify.
For example, Apache mod_zeroconf allows you to broadcast Apache sites. Your solution will be dependent on what licensing and usage rights you're dependent on.
|
1,282,452 | 1,292,620 | WIN32, C++: Is it possible to animate a window without hiding it? | I Have an edit control (a text field) which I want to animate. The animation I want is that it slides out, creating an extra line for this text field. I am able to animate my text field and able to make it larger, however to show the sliding animation I first have to hide it. This means the entire text fields slides out as if being created for the first time from nothing, instead of just adding a new line.
This is the code I have now:
SetWindowPos(hwnd, HWND_TOP, x, y, newWidth, newHeight, SWP_DRAWFRAME);
ShowWindow(hwnd, SW_HIDE);
AnimateWindow(hwnd, 300, AW_SLIDE | AW_VER_NEGATIVE);
Is it possible to show this animation without hiding it?
| To expand on Nick D's answer, here's the code to achieve what you're looking for...
.h
#define ANIMATION_TIMER 1234
#define ANIMATION_LIMIT 8
#define ANIMATION_OFFSET 4
int m_nAnimationCount;
.cpp
void CExampleDlg::OnTimer(UINT_PTR nIDEvent)
{
if (nIDEvent == ANIMATION_TIMER)
{
if (++m_nAnimationCount > ANIMATION_LIMIT)
KillTimer(EXPAND_TIMER);
else
{
CRect rcExpand;
m_edtExpand.GetWindowRect(rcExpand);
ScreenToClient(rcExpand);
rcExpand.bottom += ANIMATION_OFFSET;
m_edtExpand.MoveWindow(rcExpand);
}
}
CDialog::OnTimer(nIDEvent);
}
void CExampleDlg::OnStartAnimation()
{
m_nAnimationCount = 0;
SetTimer(ANIMATION_TIMER, 20, NULL);
}
Don't forget to set the Multiline property on the edit control (m_edtExpand)
|
1,282,994 | 1,283,021 | Fast way to pick randomly from a set, with each entry picked only once? | I'm working on a program to solve the n queens problem (the problem of putting n chess queens on an n x n chessboard such that none of them is able to capture any other using the standard chess queen's moves). I am using a heuristic algorithm, and it starts by placing one queen in each row and picking a column randomly out of the columns that are not already occupied. I feel that this step is an opportunity for optimization. Here is the code (in C++):
vector<int> colsleft;
//fills the vector sequentially with integer values
for (int c=0; c < size; c++)
colsleft.push_back(c);
for (int i=0; i < size; i++)
{
vector<int>::iterator randplace = colsleft.begin() + rand()%colsleft.size();
/* chboard is an integer array, with each entry representing a row
and holding the column position of the queen in that row */
chboard[i] = *randplace;
colsleft.erase(randplace);
}
If it is not clear from the code: I start by building a vector containing an integer for each column. Then, for each row, I pick a random entry in the vector, assign its value to that row's entry in chboard[]. I then remove that entry from the vector so it is not available for any other queens.
I'm curious about methods that could use arrays and pointers instead of a vector. Or <list>s? Is there a better way of filling the vector sequentially, other than the for loop? I would love to hear some suggestions!
| The following should fulfill your needs:
#include <algorithm>
...
int randplace[size];
for (int i = 0; i < size; i ++)
randplace[i] = i;
random_shuffle(randplace, randplace + size);
You can do the same stuff with vectors, too, if you wish.
Source: http://gethelp.devx.com/techtips/cpp_pro/10min/10min1299.asp
|
1,283,147 | 1,694,699 | Is it possible to use TDD with image processing algorithms? | Recently, I have worked in a project were TDD (Test Driven Development) was used. The project was a web application developed in Java and, although unit-testing web applications may not be trivial, it was possible using mocking (we have used the Mockito framework).
Now I will start a project where I will use C++ to work with image processing (mostly image segmentation) and I'm not sure whether using TDD is a good idea. The problem is that is very hard to tell whether the result of a segmentation is right or not, and the same problem applies to many other image processing algorithms.
So, what I would like to know is if someone here have successfully used TDD with image segmentation algorithms (not necessarily segmentation algorithms).
| The image processing tests that you describe in your question take place at a much higher level than most of the tests that you will write using TDD.
In a true Test Driven Development process you will first write a failing test before adding any new functionality to your software, then write the code that causes the test to pass, rinse and repeat.
This process yields a large library of Unit Tests, sometimes with more LOC of tests than functional code!
Because your analytic algorithms have structured behavior, they would be an excellent match for a TDD approach.
But I think the question you are really asking is "how do I go about executing a suite of Integration Tests against fuzzy image processing software?" You might think I am splitting hairs, but this distinction between Unit Tests and Integration Tests really gets to the heart of what Test Driven Development means. The benefits of the TDD process come from the rich supporting fabric of Unit Tests more than anything else.
In your case I would compare the Integration Test suite to automated performance metrics against a web application. We want to accumulate a historical record of execution times, but we probably don't want to explicitly fail the build for a single poorly performing execution (which might have been affected by network congestion, disk I/O, whatever). You might set some loose tolerances around performance of your test suite and have the Continuous Integration server kick out daily reports that give you a high level overview of the performance of your algorithm.
|
1,283,174 | 1,283,179 | C string comparison problem in c++ | I've been having trouble with comparison in my c++ program. This is the boiled down version.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
if(argc>2){cout<<"3+Args"<<endl;}else//???
if(argc==2){
cout<<"2args"<<endl;
if(argv[1]=="/hide-icons"){}
if(argv[1]=="/show-icons"){}
if(argv[1]=="/reinstall"){setAsDefault();}
if(argv[1]=="/?"){showPossibleCommands();}
if(argv[1]=="/1"){cout<<"go"<<endl;FirstRun();}
}else{showPossibleCommands();cout<<argv[0]<<endl;}
return 0;
}
When I run "programname.exe /1", my program writes "2args" but not "go". Am I missing something obvious?
| argv[1] is a char*, so by testing with == you're checking if the pointer points to the same spot as the start of the various string constants you're using... which is not going to be the case. To compare contents instead, use strcmp.
|
1,283,202 | 1,283,208 | Lightweight C++ Gui Library | I want to create GUI applications with C++ on Windows. I have downloaded Qt, and it works well, but it has so much stuff in it and so many header files that I really don't use. It is a nice framework, but it has more than just GUI.
Are there any lighter GUI libraries out there for Windows C++ that is "just GUI"?
| FLTK, if you are serious about lightweight.
http://www.fltk.org/
edit:
Blurb from the website:
FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.
I'll add that its mature and stable, too.
|
1,283,221 | 1,283,601 | Algorithm for copying N bits at arbitrary position from one int to another | An interesting problem I've been pondering the past few days is how to copy one integer's bits into another integer at a given position in the destination integer. So, for example, given the destination integer 0xdeadbeef and the source integer 0xabcd, the idea would be to get a result of 0xabcdbeef (given a destination position of 16 bits) or 0xdeabcdef (given a destination position of 8 bits).
With the arbitrary limitation of avoiding conditionals or loops (allowing myself to use just mathematical/bitwise operations), I developed the following function (C++)
int setbits(int destination, int source, int at, int numbits)
{
int ones = ((1<<(numbits))-1)<<at;
return (ones|destination)^((~source<<at)&ones);
}
where at is the place where the source bits should be copied into the destination number (0-31) and numbits is the number of bits being copied from source (1-32). As far as I can tell, this algorithm works for all values except for at = 0 and numbits = 32 (the case when the entire destination integer is being overwritten by the source integer) due to the fact that 1<<32 results in 1 (since the shift wraps around) as opposed to 0.
My questions are:
How is this normally done? Are there any particularly notable algorithms used (by notable, I'm asking if there are any particularly efficient tricks that can be used to do this)?
Does my algorithm work as well as I think it does (that is, works for all values except at = 0 and numbits = 32)?
Related to 1), is there any way to do this only using mathematical/bitwise operators? The algorithm for all values is trivial using conditions or loops, so I'm not interested in that.
Algorithm design is usually a weak point for me, so I have no idea whether or not my algorithm is 'as good as it gets' when only using mathematical/bitwise operations. Thanks
| I don't think it's the case that 1<<32 wraps (otherwise, why doesn't 2<<31 also wrap?), instead I think that internally modulus 32 is applied to the second operator, so that 1<<32 is actually equivalent to 1<<0. Also, consider changing the parameters types from "int" to "unsigned int". To get the value of "ones" without running into the "1<<32" problem, you can do this:
unsigned int ones = (0xffffffff >> (32-numbits)) << at;
I don't believe there are any "standard" methods for this kind of operation. I'm sure there are other ways of using bitwise operators in different ways to achieve the same outcome, but your algorithm is as good as any.
Having said that, though, maintainability and documentation is also important. Your function would benefit from the algorithm being documented with a comment, especially to explain how you use the bitwise XOR -- which is clever, but not easy to understand at first glance.
|
1,283,274 | 1,283,286 | What do i need to know about dynamic programming? | Started up solving UVa problems again as a way to pass time (going to the army in 6 weeks). I love writing Java, but end up using C / C++. It's not because IO is faster, no need to box data, more memory or use of unsigned, because its algorithm efficiency that counts.
In short i am slowly constructing how to/article/code base for different categories of efficient algorithms and dp is next.
Quoting Mark Twain: It ain't what you don't know that gets you into trouble. It's what you know for sure that just ain't so.
I aid assistance in building priority list what are must have efficient algorithms.
| The wikipedia article on Dynamic Programming has a section entitled "Algorithms that use dynamic programming" with many examples.
Here is another good list of practice problems in dynamic programming.
Since you referenced the UVa problem list, you should definitely take a look at Problem 103 - Stacking Boxes. The problem lends itself well to a solution using a Longest Increasing Subsequence algorithm.
|
1,283,302 | 1,283,318 | User Input of Integers - Error Handling | I'm having some trouble with certain input areas of my program. There are a few parts where the user inputs a specific integer. Even if they enter the wrong one that's all fine and dandy, but I noticed if they enter anything not of integer type like 'm' then it will loop the error message repeatedly.
I have a couple functions that have integer input in them. Here's one for an example.
void Room::move(vector<Room>& v, int exone, int extwo, int exthree, int current)
{
v[current].is_occupied = false;
int room_choice;
cout << "\nEnter room to move to: ";
while(true)
{
cin >> room_choice;
if(room_choice == exone || room_choice == extwo || room_choice == exthree)
{
v[room_choice].is_occupied = true;
break;
}
else cout << "Incorrect entry. Try again: ";
}
}
| You can use cin.good() or cin.fail() to determine whether cin could successfully deal with the input value provided. You can then use cin.clear(), if necessary, to clear the error state before continuing processing.
|
1,283,644 | 1,283,789 | Assignment Algorithm | I need to assign N entities (each with possible parents and possible children) to M computation nodes while satisfying the following optimization conditions:
Children of an entity want to be assigned to the same computation node (to maximize data locality among siblings)
The distribution of entities should be as even as possible (i.e. no overtaxing of a single node).
I'm looking for some suggestions on heuristic methods to solve this problem.
I've read http://en.wikipedia.org/wiki/Assignment%5Fproblem.
Thanks.
| I'm not sure whether 1 is a hard requirement. If so, as a first step, you should group your entities into connected components. If not, you should specify what the tradeoff between 1 and 2 is, e.g. as a cost function.
Placing the components on computation nodes is the binpacking problem, if you limit each node to N/M entities. A good approximation is the following algorithm:
sort the components by number of entities, in decreasing order
place them onto nodes as long as each node has still capacity available
when done with 2, you may have components that have not been placed. Place those on the nodes which have the smallest load so far.
|
1,283,653 | 1,283,656 | Deleting keys with subkeys | How I can delete in Windows c++ registry keys with subkeys? RegDeleteKey() doesn't work.
| SHDeleteKey can be used to delete a key and all of its sub keys.
|
1,283,866 | 1,283,883 | A template with variable number of types | I want to write a C++ template like this:
template <class Type1, class Type2, class Type3,....>
class MyClass
{
//...
};
But, "the number of types" is variable.
For example, a user can create an object with 3 types:
MyClass<int, int, int> obj;
or he can create an object with 5 types:
MyClass<int, int, int, int, int> obj;
In other words, I want the user :
1.Indicate the number of fields.
2.Set the types according to the number of fields.
how could I do this?
Thanks in advance.
| I think you should take a look at Alexandrescu's book Modern C++ Design. Chapter 3 on typelists seems to be pretty near to what you want.
|
1,284,014 | 1,284,241 | Callback in C++, template member? | Following code does NOT work, but it expresses well what I wish to do. There is a problem with the template struct container, which I think SHOULD work because it's size is known for any template argument.
class callback {
public:
// constructs a callback to a method in the context of a given object
template<class C>
callback(C& object, void (C::*method)())
: ptr.o(object), ptr.m(method) {}
// calls the method
void operator()() {
(&ptr.o ->* ptr.m) ();
}
private:
// container for the pointer to method
template<class C>
struct {
C& o;
void (C::*m)();
} ptr;
};
Is there any way to do such a thing? I mean have a non-template class callback which wraps any pointer to method?
Thanks C++ gurus!
Edit:
Please see this:
Callback in C++, template member? (2)
| Please see this
Callback in C++, template member? (2)
|
1,284,205 | 1,284,236 | wxWidgets - Alpha blending | Is there a way in wxWidget to do alpha blending operations such as multiplying the alpha of a bitmap versus the RGB of other bitmap to generate new images (such as rendering a photo as an anti-aliased circular shape).
| Though I haven't done alpha blending myself, I believe the wxGraphicContext is what you are after.
http://docs.wxwidgets.org/stable/wx_wxgraphicscontext.html
I've got flicker free drawing into the graphics context (on Win32) using the following in my paint event handler:
void OnPaint( wxPaintEvent& e )
{
wxBufferedPaintDC dc( this );
wxGraphicsContext* gdc = wxGraphicsContext::Create( dc );
// you drawing code here
}
EDIT: this email trail might offer some more insight:
http://www.nabble.com/Is-alpha-blending-implemented-when-using-DC's--td17183159.html
|
1,284,239 | 1,284,431 | Callback in C++, template member? (2) | The following callback class is a generic wrapper to "callable things". I really like its API, which has no templates and is very clean, but under the hood there is some dynamic allocation which I was not able to avoid.
Is there any way to get rid of the new and delete in the code below while maintaining the semantics and API of the callback class? I really wish I could.
Needed stuff:
// base class for something we can "call"
class callable {
public:
virtual void operator()() = 0;
virtual ~callable() {}
};
// wraps pointer-to-members
template<class C>
class callable_from_object : public callable {
public:
callable_from_object(C& object, void (C::*method)())
: o(object), m(method) {}
void operator()() {
(&o ->* m) ();
}
private:
C& o;
void (C::*m)();
};
// wraps pointer-to-functions or pointer-to-static-members
class callable_from_function : public callable {
public:
callable_from_function(void (*function)())
: f(function) {}
void operator()() {
f();
};
private:
void (*f)();
};
The callback class:
// generic wrapper for any callable
// this is the only class which is exposed to the user
class callback : public callable {
public:
template<class C>
callback(C& object, void (C::*method)())
: c(*new callable_from_object<C>(object, method)) {}
explicit callback(void (*function)())
: c(*new callable_from_function(function)) {}
void operator()() {
c();
}
~callback() {
std::cout << "dtor\n"; // check for mem leak
delete &c;
}
private:
callable& c;
};
An API example:
struct X {
void y() { std::cout << "y\n"; }
static void z() { std::cout << "z\n"; }
} x;
void w() { std::cout << "w\n"; }
int main(int, char*[]) {
callback c1(x, &X::y);
callback c2(X::z);
callback c3(w);
c1();
c2();
c3();
return 0;
}
Thanks a lot !! :-)
| YAY!!!
My best solution, using no templates, no dynamic allocation, no inheritance (just as union):
#include <iostream>
#include <stdexcept>
class callback {
public:
callback() :
type(not_a_callback) {}
template<class C>
callback(C& object, void (C::*method)()) :
type(from_object),
object_ptr(reinterpret_cast<generic*>(&object)),
method_ptr(reinterpret_cast<void (generic::*) ()>(method)) {}
template<typename T>
explicit callback(T function) :
type(from_function),
function_ptr((void (*)()) function) {}
void operator()() {
switch(type) {
case from_object:
(object_ptr ->* method_ptr) ();
break;
case from_function:
function_ptr();
break;
default:
throw std::runtime_error("invalid callback");
};
}
private:
enum { not_a_callback, from_object, from_function } type;
class generic;
union {
void (*function_ptr)();
struct {
generic* object_ptr;
void (generic::*method_ptr)();
};
};
};
Ok, its a big ugly, but it is FAST. For 20 million iterations, Boost version takes 11.8s, mine using dynamic alloc takes 9.8s and this using union takes 4.2s. And it is 60% smaller than mine using dynamic alloc, and 130% smaller than boost.
Edit: updated default constructor.
|
1,284,277 | 1,284,285 | Array values changed automatically to 0 | Today I had a strange encounter with gcc. consider the following code:
float len[ELEM+1];
len[1]=1.0; len[2]=2.0; len[3]=3.0; //length
nod[1][1] = 1;
nod[1][2] = 2;
nod[2][1] = 2;
nod[2][2] = 3;
nod[3][1] = 3;
nod[3][2] = 4; //CONNECTIVITY
for(i=1;i<nnod;i++)
for(j=1;j<nfree;j++)
/* blah blah.........*/
And a variation:
float len[ELEM+1];
len[1]=1.0; len[2]=2.0; len[3]=3.0; //length
nod[1][1] = 1;
nod[1][2] = 2;
nod[2][1] = 2;
nod[2][2] = 3;
nod[3][1] = 3;
nod[3][2] = 4; //CONNECTIVITY
len[1]=1.0; len[2]=2.0;
for(i=1;i<=nnod;i++)
for(j=1;j<=nfree;j++)
/* blah blah.........*/
The only difference is highlighted in bold.The problem is this:
When length is later printed, the first code prints len[1] and len[2] (and uses them in expressions) as 0.0000 while the second code is printing and using the correct values of those variables.
What's wrong? I'm utterly confused.:-o
Note: len is not modified anywhere else.
| You need to show us the definitions for nod. There's a good chance (based on the fact you're starting arrays at 1, not 0) that you're overwriting memory.
For example, if nod is defined as:
int nod[3][2];
the possible array subscripts are 0-2 and 0-1, not 1-3 and 1-2:
nod[0][0] nod[1][0] nod[2][0]
nod[0][1] nod[1][1] nod[2][1]
If that is the case, you're memory is almost certainly being over-written, in which case all bets are off. You could be corrupting any other piece of data.
If len is placed in memory immediately following nod, this memory overflow would explain why it's being changed. The following diagram will (attempt to) illustrate this. Let's say your nod definition is:
int nod[3][2];
but you attempt to set nod[1-3][1-2] instead of nod[0-2][0-1]:
+-----------+
+0000 | nod[0][0] |
+-----------+
+0004 | nod[0][1] |
+-----------+
+0008 | nod[1][0] |
+-----------+
+000c | nod[1][1] |
+-----------+
+0010 | nod[2][0] |
+-----------+
+0014 | nod[2][1] |
+-----------+
+0018 | len[0] | and nod[3][0], should you be foolish enough to try :-)
+-----------+
+001c | len[1] | and nod[3][1] *
+-----------+
+0020 | len[2] | and nod[3][2] *
+-----------+
C/C++ will not check regular array bounds for overflow. So, if you attempt to set nod[3][something-or-other], you'll find yourself in trouble very similar to what your question describes.
The bit patterns you're using (3 and 4) equate to IEEE754 single-precision 4.2x10-45 and 5.6x10-45 respectively so they'd certainly give 0.0000 when printing (since you don't appear to be using a format string which would give you the more precise value).
A good way to test this theory would be to output the len variables immediately before and after setting the relevant nod variables, something like:
printf ("before: len1 = %f, len2 = %f\n", len[1], len[2]);
nod[3][1] = 3;
nod[3][2] = 4;
printf ("after : len1 = %f, len2 = %f\n", len[1], len[2]);
Actual details as to how the variables are laid out in memory may be different to that described above but the theory still holds.
Two possible solutions if that turns out to be the problem.
Use zero-base arrays as C/C++ intended; or
Define them with enough space to handle your unusual use, such as int nod[4][3].
|
1,284,308 | 1,284,329 | How can I embed a PDF viewer in a cross-platform C++ application? | I need to embed a PDF viewer in my application. Is there any free software I can use?
Thanks.
| Have a look at poppler
If you have Qt have a look at this.
|
1,284,401 | 1,284,409 | How to create a Qt window behave like a message box? | I want to create a Qt popup window which will behave like a message box in Qt. That means the rest of the GUI must blocked until that popup window is dismissed. This may be a child question, but can anyone pls help me with this ?
Thanks... :)
Edit:
I want to use forms, labels, buttons and some other widget types in that popup window.
| Modal Dialogs
A modal dialog is a dialog that blocks
input to other visible windows in the
same application. Users must finish
interacting with the dialog and close
it before they can access any other
window in the application. Dialogs
that are used to request a file name
from the user or that are used to set
application preferences are usually
modal.
The most common way to display a modal
dialog is to call its exec() function.
When the user closes the dialog,
exec() will provide a useful return
value. Typically, to get the dialog to
close and return the appropriate
value, we connect a default button,
e.g. "OK", to the accept() slot and a
"Cancel" button to the reject() slot.
Alternatively you can call the done()
slot with Accepted or Rejected.
An alternative is to call
setModal(true) or setWindowModality(),
then show(). Unlike exec(), show()
returns control to the caller
immediately. Calling setModal(true) is
especially useful for progress
dialogs, where the user must have the
ability to interact with the dialog,
e.g. to cancel a long running
operation. If you use show() and
setModal(true) together to perform a
long operation, you must call
QApplication::processEvents()
periodically during processing to
enable the user to interact with the
dialog. (See QProgressDialog.)
|
1,284,529 | 1,284,599 | Enums: Can they do in .h or must stay in .cpp? | If I have something like:
enum
{
kCP_AboutBox_IconViewID = 1,
kCP_AboutBox_AppNameViewID = 2,
kCP_AboutBox_VersionViewID = 3,
kCP_AboutBox_DescriptionViewID = 4,
kCP_AboutBox_CopyrightViewID = 5
};
in my .cpp can it go in the .h?
More so, what other lesser know things can you put in a .h besides class definitions, variables, etc, etc
| A .h file is essentially just code which, at compile time, is placed above any .cpp (or .h file for that matter) that it's included in. Therefore you CAN just place any code from the .cpp file into the .h and it should compile fine.
However it's the design which is important. Your code (e.g. your enum) SHOULD be placed in the .h file if you need to expose it to the code you're including the .h file. However if the enum is only specific to the code in your header's .cpp implementation, then you should encapsulate it just within the .cpp file.
|
1,284,619 | 1,286,496 | GCC C++ (ARM) and const pointer to struct field | Let's say there is a simple test code
typedef struct
{
int first;
int second;
int third;
} type_t;
#define ADDRESS 0x12345678
#define REGISTER ((type_t*)ADDRESS)
const int data = (int)(®ISTER->second)*2;
int main(void)
{
volatile int data_copy;
data_copy = data;
while(1) {};
}
Which is compiled in CodeSourcery G++ (gcc 4.3.2) for bare metal ARM. It also has a very standard linker script.
When compiled in C (as main.c) the object "data" goes into Flash, as expected. When compiled in C++ (as main.cpp) this object goes into RAM, and additional code is added which does nothing more than copy the value from Flash to RAM (the value is already calculated, just copy!). So the compiler can calculate the address, but somehow doesn't want to "just
use it". The root of the problem is the multiplication of the address - without "*2" multiplication both versions work as expected - "data" is placed in Flash. Also - when "data" is declared as:
const int data = (int)(REGISTER)*2;
also everything is fine.
All files for C and C++ compilation are identical, the only difference is the call to compiler - g++ for main.cpp, gcc for main.c (with differences in the level of warnings, and c++ has RTTI and exceptions disabled).
Is there any easy and elegant way to overcome this "C++ problem"? I do require such operations for creating const arrays of addresses of bits in bitband region of Cortex-M3. Is this a bug, or maybe that is some strange limitation of the C++ compiler?
I know that I can create data objects in "C" files and just "extern"-include them in C++, but that's not very elegant [;
Thank you for all help!
| The right solution is using the offsetof() macro from the stddef.h header.
Basically this:
const int data = (int)(®ISTER->second)*2;
has to be replaced with
#include <stddef.h>
const int data = (int)(REGISTER + offsetof(type_t,second))*2;
And then the object is placed in Flash both for C and C++.
|
1,284,674 | 1,285,036 | How Do I Stop An Application From Opening | I want to write a small app that sits in my tray and that allows me to select an executable and prevent it from opening.
The UI of the app is easy to do using WinForms.
What I want to know is how to detect if a certain exe has been lauched and then how to stop it from running. I'm pretty sure I'll have to dig down into some Win32 stuff but I have no experience in that area, hence this post.
There is an existing app similar to this, but I can't for the life of me remember what it's called. It was written in VB6 and it's open source too.
Any help is much appreciated.
| Rather than trying to kill the process when it runs, how about stopping it from running in the first place?
Changing what happens when the shell tries to launch an application is simple - add a new registry key to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
To test this I added a registry key called notepad.exe and within this the string value Debugger with the value calc.exe. Now whenever I try and run notepad calc opens. The following is the exported registry key.
REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe]
"Debugger"="calc.exe"
Having made this change I've not yet managed to open notepad, not bad for a no code solution. If you need to be 100% certain that the application never runs you could always add a "kill" solution too as detailed by others.
|
1,284,701 | 1,284,721 | Weird in Header Files | I have lines in header files that are like:
public:
//! @name Constructor / Destructor
//@{
//! Constructor.
CP_AboutBox( CP_Application_Imp *inOwnerApp );
virtual ~CP_AboutBox() throw();
//@}
//! @name Instance
//@{
static CP_AboutBox *Instance();
//@}
//! @name Display
//@{
void Display( const CP_String& inDescription = CP_String("") );
//@}
//! @name Setters
//@{
What is all this @name Instance and @name Display?
is it Doxygen?
| Yes, see for example this section from the Doxygen documentaion which explains it.
|
1,284,744 | 1,284,778 | Visual C++ class testing | Is there any way to easily test C++ classes in java way.
In java you can add static function main and run it directly from IDE
class Foo{
...
public static void main(String args[])
{
System.out.println("Test class foo here");
}
}
is it possible to do it in Visual C++ ?
Of course you can create another project, but it is bad solution(you sould create project, and then add it to solution or run another copy of Visual Studio)
Another way is to modify main() function, or CWinApp::InitInstance() but if you change file
Foo.h, VS will rebuild all files from project, depending on it (we just want to test Foo.h & Foo.cpp)
The best way i founded is to create another project (console), add Foo.h and Foo.cpp to it, add public static function run() to my class Foo and run it from main() function in console project like this
//unitTester.cpp
include "Foo.h"
int main(...){
Foo::run();
return 0;
}
in such way i can test my class Foo separately (without recompiling the big project)
| When I feel like writing unit tests, I usually add another project that links in the test code + the classes being tested. The test code I write using the Boost Test Library, which nicely integrates with Visual Studio. I make my actual project dependent on the test project. The test project runs its executable as a post-build step. Therefore, as long as the tests fail, I cannot even build the main project.
|
1,284,766 | 1,284,809 | Console get key press w/o windows messages c++ | Is there any way to get the last key press in a console without using Windows messages or the std::cin stream? I've heard that there is a function in the standard library. Solutions should preferably be as portable as possible. Thanks for your help in advance.
| There's conio.h but it's not technically standard. On Linux, my first Google hit suggests termios.h.
|
1,285,137 | 1,285,168 | Is there any difference in speed in manipulating different types of variables? | This is in reference to C++ and using the Visual Studio compilers.
Is there any difference in speed when reading/writing (to RAM) and doing mathematical operations on different types of variables such as bool, short int, int, float, and doubles?
From what I understand so far, mathematical operations with doubles takes much longer (I am talking about 32 bit processors, I know little about 64 bit processors) than, say, operations with floats.
How then do operations (reading/writing to ram and elementary math) with float and int compare? How about int and short int, or even differences between signed and unsigned versions of each of the types? Is there any one data type that would be most efficient to work with as low number counters?
Thanks,
-Faken
| There are two different questions here: speed when reading/writing, and arithmetic performance. Those are orthogonal. When reading or writing a large array, of course, the speed depends on the amount of bytes read as O(N), so using short over int (considering VC++) would slash the time by ~1/2.
For arithmetic, once the operands are in registers, the size of the type doesn't matter so much. IIRC, between types in the same category, it is actually the same (so short isn't any faster or slower than int). Using 64-bit integer types on a 32-bit platform will have a penalty, naturally, since there's no single instruction to handle that. Floating-point types, on the other hand, are simply slower than all integral types, even though sizeof(float)==sizeof(int) on VC++. But, again, operations on float aren't any faster than operations on double; this is assuming default FPU settings, which promote all operands to 80-bit extended floats - this can be disabled to squeeze out a bit more out of using floats, IIRC.
The above is VC++ and x86 specific, as requested by the question. Other platform, and especially other architecture, can differ radically.
The best one data type that is most efficient to work with as number counter (low or not) is int - usually regardless of the architecture and implementation (as the Standard recommends it to be the preferred word size of the platform).
|
1,285,454 | 1,285,517 | setting a default union member | i'm using templated unions to both assure myself that i always get a 64-bit field for pointers (even on 32-bit machines since there is transmission of data to a 64-bit machine occurring) and to save both the user and myself casting.
template <typename type> union lrbPointer
{
uint64_t intForm;
type ptrForm; //assumed that type is a pointer type
};
//usage
lrbPointer<int*> myPointer;
int integers[4];
myPointer.ptrForm = integers;
myPointer.intForm += 2; //making it easy to jump by less then sizeof(int)
this is working well for me, but i would really love to find a way to make a default member. so that the user does not need to use a .ptrForm after the pointer they wish to use.
| You can use a conversion operator, along with a constructor, so you can transfer between the types:
template <typename PtrType>
union IntPointer
{
uint64_t intForm;
PtrType ptrForm;
IntPointer(PtrType ptr) :
ptrForm(ptr)
{
}
operator PtrType(void) const
{
return ptrForm;
}
};
int main(void)
{
IntPointer<float*> f = new float; // constructor
float *theFloat = f; // conversion operator
delete theFloat;
}
That said, I think your treading on thin ground. :|
|
1,285,714 | 62,433,868 | Lightweight, portable C++ fibers, MIT license | I would like to get ahold of a lightweight, portable fiber lib with MIT license (or looser). Boost.Coroutine does not qualify (not lightweight), neither do Portable Coroutine Library nor Kent C++CSP (both GPL).
Edit: could you help me find one? :)
| If Boost seems to heavy, helpful people have extracted the relevant parts of Boost (fcontext) as a standalone library, e.g. deboost.context.
|
1,286,363 | 1,520,384 | How to get the font size from CMFCPropertyFontProperty | I'm using this code block to get the font name, style and size selected by the user from the font dialog of CMFCPropertyFontProperty control. I'm already able to get the name and the style, but the size seems to return a different value.
CMFCPropertyGridProperty* pCurSel = m_wndPropList.GetCurSel();
CMFCPropertyGridFontProperty* pFontProp = dynamic_cast<CMFCPropertyGridFontProperty*>(pCurSel);
if (pFontProp) {
LPLOGFONT font_info = pFontProp->GetLogFont();
INT nSize = 0;
nSize = font_info->lfHeight;
//nSize seems to return a negative value... :(
}
I realize that there's a formula for it:
lfHeight = -MulDiv(PointSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);
But I can't seem to get it working... how do I get the hDC from CMFCPropertyFontProperty? please help...
| You can just use GetDC(NULL); to get an HDC for the screen which I assume will be the same as what the font dialog will use.
The LOGFONT documentation describes the meaning of +ve and -ve values for the lfHeight member,
http://msdn.microsoft.com/en-us/library/dd145037(VS.85).aspx
|
1,286,394 | 1,286,412 | For-loop in C++ using double breaking out one step early, boundary value not reached | I have a simple C++ program compiled using gcc 4.2.4 on 32-bit Ubuntu 8.04. It has a for-loop in which a double variable is incremented from zero to one with a certain step size. When the step size is 0.1, the behavior is what I expected. But when the step size is '0.05', the loop exits after 0.95. Can anyone tell me why this is happening? The output follows the source code below.
#include <iostream>
using namespace std;
int main()
{
double rangeMin = 0.0;
double rangeMax = 1.0;
double stepSize = 0.1;
for (double index = rangeMin; index <= rangeMax; index+= stepSize)
{
cout << index << endl;
}
cout << endl;
stepSize = 0.05;
for (double index = rangeMin; index <= rangeMax; index+= stepSize)
{
cout << index << endl;
}
return 0;
}
OUTPUT
sarva@savija-dev:~/code/scratch$ ./a.out
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95
sarva@savija-dev:~/code/scratch$
| When using floating point values not every value is exactly representable, 0.95+0.05 > 1 because 0.95 is not exactly representable by a double value.
See what Wikipedia has to say about floating point accuracy.
If you look at the IEEE floating point converter you'll see that the value of 0.95 in 64 bit floating point (double) is 0-01111111110-1110011001100110011001100110011001100110011001100110 by entering this in a floating point calculator you get the value is 0.95000016 and adding 0.05 to that takes you over the 1.0 mark.
This is why you should never use floating points in loops (or more generally compare the result of floating point calculation to an exact value).
|
1,286,411 | 1,286,420 | C++ and const - accessing a member function of a const reference | I have this snippet of code here. The intention is to make a copy of initialData. Since I am not modifying initialData in any way, I figure that I should pass it as a const reference. However, I keep getting this message when compiling.
.\src\Scene\SceneAnimationData.cpp(23)
: error C2662:
'SceneTrackerData::getRect' : cannot
convert 'this' pointer from 'const
SceneTrackerData' to 'SceneTrackerData
&'
#include "SceneTrackerData.h"
void SceneAnimationData::SetupData(const SceneTrackerData &initialData)
{
// getRect(), points() and links() all return const pointers
CloneRect(initialData.getRect());
ClonePoints(initialData.points()->values());
CloneLinks(initialData.links()->values());
}
void SceneAnimationData::CloneRect(const QGraphicsRectItem * initialRect)
{
if (initialRect != NULL)
{
QPointF position = initialRect->scenePos();
QRectF rect = initialRect->rect();
initialRect = new QGraphicsRectItem(rect);
initialRect->setPos(position);
}
}
void SceneAnimationData::CloneLinks(const QList<QGraphicsLineItem*> links)
{
links_ = new QList<QGraphicsLineItem*>(*links);
}
void SceneAnimationData::ClonePoints(const QList<QGraphicsEllipseItem*> points)
{
points_ = new QList<QGraphicsEllipseItem*>(*points);
}
| Without the definition of SceneTrackerData, it's hard to say, but likely that function (SceneTrackerData::getRect) is not marked as const.
That is, what is (guessing):
const Rect& SceneTrackerData::getRect(void)
Should be:
const Rect& SceneTrackerData::getRect(void) const
// ^
// |
// does not logically modify the object
|
1,286,449 | 1,286,781 | Auto-cast two 3rd party classes? | I'm using two 3rd party libraries, which both implement their own 2D vector class. Unfortunately, I have to work with both of them, so is there anyway I can write some "friend" functions so that one can automatically be converted to the other when I try to use them in functions from the other library?
| Conversion operators have to be member functions.
In situations like this, I have used a convert<X,Y> function template, with full specialisations or overloads for each pair of types that I want to "cast". In this case, you wouldn't need the template, just two overloads, one in each direction, because for a given X there's only ever one thing you convert it to.
Then it's rarely any trouble to switch between one and the other (the notable exception being when you're using template code which requires that one parameter type be convertible to another). You can easily see in the code the boundary between the two APIs, without introducing much noise.
The reason I've had this situation a lot is writing OS abstraction layers - the underlying OS has one set of objects or opaque handles for various OS concepts, and the API you're implementing has another. It's much nicer to just "convert" from one set of concepts to the other, without having ConvertHostMutexToGuestMutex, ConvertGuestMutexToHostMutex, ConvertHostSocketOptsToGuestSocketOpts etc. The disadvantage is the usual one with widespread overloading, that it's not necessarily obvious where the functions are actually defined.
|
1,286,578 | 1,286,600 | Bignum libraries for windows? | Are there any bignum libraries that are good for Windows use? I looked at GMP, but unfortunately it does not look like it can be compiled on Windows...(I'm going to be doing some custom RSA and hashing routines)
Thanks.
| People provide pre-compiled binaries for gmp on Windows; there are also instructions for compiling it yourself. Another option would be the bignum library of OpenSSL.
|
1,286,614 | 1,286,645 | operator char* in STL string class | Why doesn't the STL string class have an overloaded char* operator built-in? Is there any specific reason for them to avoid it?
If there was one, then using the string class with C functions would become much more convenient.
I would like to know your views.
| Following is the quote from Josuttis STL book:
However, there is no automatic type
conversion from a string object to a
C-string. This is for safety reasons
to prevent unintended type conversions
that result in strange behavior (type
char* often has strange behavior) and
ambiguities (for example, in an
expression that combines a string and
a C-string it would be possible to
convert string into char* and vice
versa). Instead, there are several
ways to create or write/copy in a
C-string, In particular, c_str() is
provided to generate the value of a
string as a C-string (as a character
array that has '\0' as its last
character).
|
1,286,662 | 1,286,762 | Is there any sample code to read thumbnail from Jpeg exif header? | I am writing application using c++, in windows.
I want to get a thumbnail from jpeg, without decoding the whole image.
How Can I read thumbnail from jpeg exif header?
Can any one offer me a some sample code?
Many thanks!
| Unsurprisingly the library is called libexif has win32 port, and there is sample code for reading thubnail from file
|
1,286,771 | 1,286,785 | Adding values to a 3-d vector in c++ | I would like to use a 3-d Vector to store and add values between some calculations in c++.
I'm having problems adding the third dimension to my vector.
What I would like to achieve is a vector that for each iteration puts in a 2-D vector and here only the first values for each vector...
So The input would look something like this
1 3 7 9
- - - -
Then Later on I would like to add values to the places marked with -
so in the end the matrix would look something like this(for every iteration)(only 2-d shown...)
1 3 7 9
2 5 7
3 2
1
Right now I'm having trouble adding the first elements to it. And i'm using the sollist 3-D vector as a global vector.
My values array all have the same amount of elements that are > 0.5 so that's not where the error is.
vector<vector<vector<int>>>sollist;
void sol(array& values, int& iter)
{int i;
sollist.push_back ( vector<vector<int>>() );
for (i=0;i<10;i++)
if (values[i]>0.5)
sollist[iter][0].push_back(i);
}
Thank you very much for any help and for an excellent forum...
/Buxley
| I think you have to do something like this.
sollist.push_back(vector<vector<int>>());
sollist[0].push_back(vector<int>());
sollist[0][0].push_back(value);
|
1,286,787 | 1,286,876 | Any approach to peek memory data structure of C/CPP application? | ... like how many memory consumed by what / how many objects, as in JVM heap dump file. Our service process is consuming remarkable memory, which is being complained by others living in a same OS.
The applications structure is weird, it leveraged reverse JNI to call java interface from c++ code, also it's a network application, all these make it almost impossible to use tools like valgrind or purify.
Any suggestion would be appriciated.
| You could overload new/delete and track memory usage that way.
|
1,286,842 | 1,286,924 | How do I run XPath queries in QT? | How do I run an XPath query in QT?
I need to sort out certain tags with specific values in a certain attribute. The QXmlQuery documentation is anything but legible.
The schema I'm parsing is the Rhythmbox DB format:
<rhythmdb version="1.6">
<entry type="ignore">
<title></title>
<genre></genre>
<artist></artist>
<album></album>
<location>file:///mnt/disk/music/Cover.jpg</location>
<mountpoint>file:///mnt/disk</mountpoint>
<mtime>1222396828</mtime>
<date>0</date>
<mimetype>application/octet-stream</mimetype>
<mb-trackid></mb-trackid>
<mb-artistid></mb-artistid>
<mb-albumid></mb-albumid>
<mb-albumartistid></mb-albumartistid>
<mb-artistsortname></mb-artistsortname>
</entry>
<entry type="song">
<title>Bar</title>
<genre>Foobared Music</genre>
<artist>Foo</artist>
<album>The Great big Bar</album>
<track-number>1</track-number>
<disc-number>1</disc-number>
<duration>208</duration>
<file-size>8694159</file-size>
<location>file:///media/disk/music/01-Foo_-_Bar.ogg
<mountpoint>file:///media/disk
<mtime>1216995840</mtime>
<first-seen>1250478814</first-seen>
<last-seen>1250478814</last-seen>
<bitrate>301</bitrate>
<date>732677</date>
<mimetype>application/x-id3</mimetype>
<mb-trackid></mb-trackid>
<mb-artistid></mb-artistid>
<mb-albumid></mb-albumid>
<mb-albumartistid></mb-albumartistid>
<mb-artistsortname></mb-artistsortname>
</entry>
</rhythmdb>
This is your basic XML Schema which has a collection of structured entries. My intention was to filter out the entries with the type 'ignore'.
| The relevant documentation is at: http://qt-project.org/doc/qt-4.8/qxmlquery.html#running-xpath-expressions.
The solution I came to was to use QXmlQuery to generate an XML file then parse it again using QDomDocument.
RhythmboxTrackModel::RhythmboxTrackModel()
{
QXmlQuery query;
QXmlQuery entries;
QString res;
QDomDocument rhythmdb;
/*
* Try and open the Rhythmbox DB. An API call which tells us where
* the file is would be nice.
*/
QFile db(QDir::homePath() + "/.gnome2/rhythmbox/rhythmdb.xml");
if ( ! db.exists()) {
db.setFileName(QDir::homePath() + "/.local/share/rhythmbox/rhythmdb.xml");
if ( ! db.exists())
return;
}
if (!db.open(QIODevice::ReadOnly | QIODevice::Text))
return;
/*
* Use QXmlQuery to execute and XPath query. Check the version to
* make sure.
*/
query.setFocus(&db);
query.setQuery("rhythmdb[@version='1.6']/entry[@type='song']");
if ( ! query.isValid())
return;
query.evaluateTo(&res);
db.close();
/*
* Parse the result as an XML file. These shennanigans actually
* reduce the load time from a minute to a matter of seconds.
*/
rhythmdb.setContent("" + res + "");
m_entryNodes = rhythmdb.elementsByTagName("entry");
for (int i = 0; i < m_entryNodes.count(); i++) {
QDomNode n = m_entryNodes.at(i);
QString location = n.firstChildElement("location").text();
m_mTracksByLocation[location] = n;
}
qDebug() << rhythmdb.doctype().name();
qDebug() << "RhythmboxTrackModel: m_entryNodes size is" << m_entryNodes.size();
}
In case anyone is wondering, this is my code taken from a recent branch of the Mixxx project, specifically the features_looping branch.
The things I dislike about this solution are:
Parsing the XML twice
Concatenating the result with a starting and ending tag.
|
1,286,950 | 1,287,060 | Macro recursive expansion to a sequence | Is it possible to define a C/C++ macro "BUILD(a, i)" which expands to "x[0], x[1], x[2], ..., x[i]" ? Like in
#define BUILD(x, 0) x[0]
#define BUILD(x, 1) x[0], x[1]
#define BUILD(x, 2) x[0], x[1], x[2]
...
It seems BOOST_PP_ENUM_PARAMS could do the job. I suppose I could just #include boost, but I'm interested in knowing how and why it works, anyone can explain?
I would like to call a function f(int, ...) which takes N int arguments x[i], 0 <= i < N. Where N is known to be ceil(sizeof(A) / sizeof(B)). So unfortunately, I cannot use varargs or templates.
| It is possible, but you have to do some manual work and have an upper limit.
#define BUILD0(x) x[0]
#define BUILD1(x) BUILD0(x), x[1]
#define BUILD2(x) BUILD1(x), x[2]
#define BUILD3(x) BUILD2(x), x[3]
#define BUILD(x, i) BUILD##i(x)
And note that i should be an integer literal, not a constant computed value.
BTW, the preprocessor is more powerful than what is usually though, but the use of that power is quite tricky. Boost provides a library which eases some things, including iteration. See Boost Preprocessor Library. There is another library for such things, but its name escapes me at the moment.
Edit: The boost preprocessor library uses a similar technique. With additional tricks to solve some corner cases problems, share implementation macros between higher level facilities, work around compiler bugs, etc... the usual boost complexity which is normal in the context of a general purpose library but which at times prevents easy understanding of the implementation principles. Probably the most noticeable trick is to add an indirection level so that if the second parameter can be a macro, it is expanded. I.e. with
#define BUILD_(x, i) BUILD##i(x)
#define BUILD(x, i) BUILD_(x, i)
one can make the call
#define FOO 42
BUILD(x, FOO)
which isn't possible with what I exposed.
|
1,287,306 | 1,287,357 | Difference between string and char[] types in C++ | For C, we use char[] to represent strings.
For C++, I see examples using both std::string and char arrays.
#include <iostream>
#include <string>
using namespace std;
int main () {
string name;
cout << "What's your name? ";
getline(cin, name);
cout << "Hello " << name << ".\n";
return 0;
}
#include <iostream>
using namespace std;
int main () {
char name[256];
cout << "What's your name? ";
cin.getline(name, 256);
cout << "Hello " << name << ".\n";
return 0;
}
(Both examples adapted from http://www.cplusplus.com.)
What is the difference between these two types in C++? (In terms of performance, API integration, pros/cons, ...)
| A char array is just that - an array of characters:
If allocated on the stack (like in your example), it will always occupy eg. 256 bytes no matter how long the text it contains is
If allocated on the heap (using malloc() or new char[]) you're responsible for releasing the memory afterwards and you will always have the overhead of a heap allocation.
If you copy a text of more than 256 chars into the array, it might crash, produce ugly assertion messages or cause unexplainable (mis-)behavior somewhere else in your program.
To determine the text's length, the array has to be scanned, character by character, for a \0 character.
A string is a class that contains a char array, but automatically manages it for you. Most string implementations have a built-in array of 16 characters (so short strings don't fragment the heap) and use the heap for longer strings.
You can access a string's char array like this:
std::string myString = "Hello World";
const char *myStringChars = myString.c_str();
C++ strings can contain embedded \0 characters, know their length without counting, are faster than heap-allocated char arrays for short texts and protect you from buffer overruns. Plus they're more readable and easier to use.
However, C++ strings are not (very) suitable for usage across DLL boundaries, because this would require any user of such a DLL function to make sure he's using the exact same compiler and C++ runtime implementation, lest he risk his string class behaving differently.
Normally, a string class would also release its heap memory on the calling heap, so it will only be able to free memory again if you're using a shared (.dll or .so) version of the runtime.
In short: use C++ strings in all your internal functions and methods. If you ever write a .dll or .so, use C strings in your public (dll/so-exposed) functions.
|
1,287,410 | 1,288,356 | How to serialize a pointer into an array of ints? | I know that converting a pointer to one int is unsafe, because the pointer can be bigger than the int in some architectures (for instance in x86_64).
But what about converting the pointer to several ints, an array of them? If the pointer size is 2 times bigger than int then convert pointer* to int[2].
The number of needed ints then is ceil(sizeof(pointer*)/sizeof(int)).
I need to do this because there is a function which takes ints as arguments and I want to pass a pointer to it.
| Yet another solution:
#define BIG_ENOUGH 4
typedef union {
int buffer[BIG_ENOUGH];
pointer_t* pointer;
} proxy_t;
static_assert(sizeof(pointer_t*) <= BIG_ENOUGH*sizeof(int));
// before calling the function
proxy_t proxy;
proxy.pointer = the_pointer;
// call to the function, cannot be generic here
f(proxy.buffer[0], proxy.buffer[1], proxy.buffer[2], proxy.buffer[3]);
// how to recover the value of the pointer
void f(int b0, int b1, int b2, int b3) {
proxy_t proxy = { { b0, b1, b2, b3 } };
the_pointer = proxy.pointer;
}
|
1,287,425 | 1,288,802 | Automated Testing for C/C++ GUI Applications | I have a GUI application written in C/C++ using gcc. I need some recommendations for writing an automated test system for it. What tools/scripting should be used? The application runs on Windows.
| My recommendation is PyWinAuto, open source tool, python based tests (fast and easy to develop) and work on win32 level.
http://pywinauto.openqa.org/
|
1,287,805 | 1,351,979 | How to predeliver WMA DRM licenses? | I'm trying to install WMA DRM licenses files silently so that users would not have to play each song and acknowledge for each license.
I figured out that I need to do something like this :
HRESULT res = CoCreateInstance(__uuidof(RMGetLicense),NULL,CLSCTX_ALL,__uuidof(IRMGetLicense ),(void**) &pLicense );
res = pLicense->GetLicenseFromURL(NULL, bstrURL);
The bstrURL is expected to contain a keyID as a parameter, which allow to retrieve the file matching with the music file. I can't find how to get this keyID back from the WMA file.
I may get the problem wrongly though. Am I in the good way ?
| You have to pass header object as a first parameter. More information is in MSDN
|
1,287,857 | 1,290,519 | Where do I find the list of unloaded modules in a Windows process? | I have some native (as in /SUBSYSTEM:NATIVE) Windows programs that I'd like to generate minidumps for in case they crash. Normally, I'd use dbghelp.dll, but since native processes can only use functions exported from ntdll.dll, I can't.
So I've implemented the dumper myself. It's almost done, but unfortunately, I've been unable to locate the list of unloaded modules in the crashed process (the list is certainly stored somewhere, since WinDbg is able to display it).
Where do I find the list of unloaded modules in a Windows process?
Edit: The list is certainly stored somewhere in the process memory, WinDbg can display the list even if I attach it after the modules were unloaded. There's also a note in the documentation of WinDbg:
Microsoft Windows Server 2003 and later versions of Windows maintain an unloaded module list for user-mode processes. [...]
| See RtlGetUnloadEventTrace and RtlGetUnloadEventTraceEx.
I am not entirely sure about how it works, but I believe the actual list is stored by ntdll.dll in the loader code. It keeps track of the 16 (or 64, according to MSDN) last unloaded DLLs in the specific process. The information is not linked from PEB or PEB_LDR_DATA.
|
1,287,884 | 1,288,010 | Synchronizing DataGridView (DataTable) with the DB | I have the following situation: there is a table in the DB that is queried when the form loads and the retrieved data is filled into a DataGridView via the DataTable underneath. After the data is loaded the user is free to modify the data (add / delete rows, modify entries).
The form has 2 buttons: Apply and Refresh. The first one sends the changes to the database, the second one re-reads the data from the DB and erases any changes that have been made by the user.
My question is: is this the best way to keep a DataGridView synchronized with the DB (from a users point of view)?
For now these are the downsides:
the user must keep track of what he is doing and must press the button every while
the modifications are lost if the form is closed / app crash / ...
I tried sending the changes to the DB on CellEndEdit event but then the user also needs some Undo/Redo functionality and that is ... well ... a different story.
So, any suggestions?
| I would say that the way you are currently doing it is fine. If you start attempting to update the database while the user is still making edits you can run in to issues updating or modfiying things that the user may ultimately decide they did not want to change. Additionally this has the chance to greatly increase the number of database calls.
Forcing the user to click apply helps ensure that only the changes the user actually wants are sent to the database.
As for losing the changes if the app crashes before applying them, I would be more concernced with why the app is crashing.
|
1,288,009 | 1,289,118 | Detecting locale from unicode string in c++ | I have a string and I want to check if the content is in English or Hindi(My local language). I figured out that the unicode range for hindi character is from U0900-U097F.
What is the simplest way to find if the string has any characters in this range?
I can use std::string or Glib::ustring depending on whichever is convenient.
| Here is how you do it with Glib::ustring :
using Glib::ustring;
ustring x("सहस"); // hindi string
bool is_hindi = false;
for (ustring::iterator i = x.begin(); i != x.end(); i ++)
if (*i >= 0x0900 && *i <= 0x097f)
is_hindi = true;
|
1,288,179 | 1,288,188 | how to refer to the current struct in an overloaded operator? | I have a struct for which i want to define a relative order by defining < , > , <= and >= operators. actually in my order there won't be any equality, so if one struct is not smaller than another, it's automatically larger.
I defined the first operator like this:
struct MyStruct{
...
...
bool operator < (const MyStruct &b) const {return (somefancycomputation);}
};
now i'd like to define the other operators based on this operator, such that <= will return the same as < and the other two will simply return the oposite.
so for example for the > operator i'd like to write something like
bool operator > (const MyStruct &b) const {return !(self<b);}
but i don't know how to refere to this 'self' since i can refere only to the fields inside the current struct.
whole is in C++
hope my question was understandable :)
thank you for the help!
| Self is *this.
That is, this is a pointer to the current object, so you need to dereference it to get the actual object.
|
1,288,183 | 1,288,363 | Downgrading from Boost 1.37 to 1.34 | I have to update an application to use Boost 1.34 instead of 1.37, and it's causing me a ton of trouble.
One of the biggest problems at the moment is that I don't know Boost threads very well. With 1.34, I get...
error C2039: 'this_thread' : is not a member of 'boost'
...for the code
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
boost::posix_time is not in 1.34 either.
Does anyone know the equivilant Boost 1.34 function calls?
| boost::thread::sleep takes a struct xtime in 1.34.1. Try this:
struct xtime timeout;
timeout.sec = 0;
timeout.nsec = 500 * 1000000;
boost::thread::sleep(timeout);
|
1,288,216 | 1,288,354 | Metaclasses and Reflection in C++ | i received a small problem to resolve in my free time regarding changing an objects behavior and also the class behavior at runtime in C++. I read a little bit and found this link, really useful for me. http://www.vollmann.ch/en/pubs/meta/meta/meta.html Mr. Volmann made a Meta object protocol(MOP) for defining classes at runtime, more exactly their properties.
I tried to add methods in the same matter, at runtime, with dynamically loading dlls but the objects weren't aware about their new added behaviors. i saved the details about the methods in the dlls in xml files, and when i wanted to add a new behavior to a class/object i parsed the xml files and loaded only the DLL i needed, but this wasn't flexible enough..
this is just a study case, so if you have any guidance to give please do. I don't have much experience in C++ but i liked the challenge.
Thank you in advance.
| You could try to create some kind of base class for all of your classes. This class has some kind of add method for function pointers. Each fp is assigned some kind of handle or string. Later you can then call the added function via some kind of generic call method.
for the arguments of the function - you'll need some way to pass this to the function for referencing the data of the class. Perhaps you'll encapsule the data in some kind of struct and pass a reference/pointer to the struct. For other arguments, you could use some list of pointers or take a look at bind.
Be aware - this is a major undertaking as C++ is not created with these kind of things in mind.
|
1,288,566 | 1,288,629 | CPP to Java conversion | Here's my scenario. I have an application written in C++ but not the complete source but the "meat" of it is there. I also have a compiled exe of this application. It communicates to a server somewhere here on our network. I am trying to replicate the C++ code in java, however it uses dwords and memory references, sizeof etc, all things that don't exist in java since it manages it's own memory. It builds this large complex message and then fires it over the network. So I am basically sniffing the traffic and inspecting the packet and trying to hardcode the data it's sending over to see if I can get a response from the server this way. However I can't seem to replicate the message perfectly. Some of it, such as the license code it sends is in "clear hex", that is, hex that translates into ascii, where-as some other portions of the data are not "clear hex" such as "aa" which does not translate into ascii (or at least a common character set?? if that makes any sense I'm not sure).
Ideally I'd like to not do it like this, but it's a stepping stone to see if can get the server to respond to me. One of the functions is for the application to register itself and that's the one I am trying to replicate.
Some of my assumptions above may be wrong, so I apologize in advance. Thanks for your time.
| In Java, all "character" data is encoded as Unicode (and not ASCII). So when you talk to something outside, you need to map the internal strings to the outside world. There are several ways to do it:
Use a ByteArrayOutputStream. This is basically a growing buffer of bytes to which you can append. This allows you to build the message using bytes.
Use getBytes(encoding) where encoding is the encoding the other side understands. In your case, that would be "ASCII" for the text parts.
In your case, you probably need both. Create a byte buffer and then append strings and bytes to it and then send the final result (getByteArray()) via the socket API.
|
1,288,669 | 1,288,705 | Overloading operators in C++ | See edit at the end
I am trying to overload the + operator in C++ to allow me to add two complex numbers. (add the real and add the imaginary).
Here is my overloaded function:
ComplexNum operator+(ComplexNum x, ComplexNum y){
ComplexNum result;
result.real = (x.getReal() + y.getReal());
result.imag = (x.getImag() + y.getImag());
return result;
}
My Complex number constructor takes in two ints and assigned the first to int real and second to int imag.
When I try add them:
ComplexNum num1 = ComplexNum(1,1);
ComplexNum num2 = ComplexNum(2,3);
ComplexNum num3;
num3 = num1 + num2;
printf("%d",num3.getReal());
I get 0 as a result. The result should be 3 (the real parts of num1 and num2 added)
EDIT: I figured out what was wrong. I had .getReal() and .getImage() returning double.
| Since the arguments of operator+ are declared as values, not references, they will be passed by copy, so if the copy-constructor of ComplexNum doesn't work, that could cause x and y to have a real part of 0.
It's also possible that the addition works, but you lose the real part when you invoke the assignment operator of num3.
Or maybe it's simply the getReal() method that is broken.
|
1,288,761 | 1,288,775 | UINT16 value appears to be "backwards" when printing | I have a UINT8 pointer mArray, which is being assigned information via a *(UINT16 *) casting. EG:
int offset = someValue;
UINT16 mUINT16 = 0xAAFF
*(UINT16 *)&mArray[offset] = mUINT16;
for(int i = 0; i < mArrayLength; i++)
{
printf("%02X",*(mArray + i));
}
output: ... FF AA ...
expected: ... AA FF ...
The value I am expecting to be printed when it reaches offset is to be AA FF, but the value that is printed is FF AA, and for the life of me I can't figure out why.
| You are using a little endian machine.
|
1,288,996 | 1,291,142 | Is there a database access library for C and/or C++ with a similar interface to Perl's DBI? | I'm willing to write a subset of Perl's DBI interface for libodbc (or unixODBC) in C++.
I believe doing so will allow me concentrate better on my goal.
BTW, I prefer avoiding to reinvent the wheel, if of course something similar is already out there.
| NVM, no odbc interface, but it is DBI like (seeing as DBI doesn't use odbc except in DBD::ODBC)
libdbi - http://libdbi.sourceforge.net/
libdbi implements a
database-independent abstraction layer
in C, similar to the DBI/DBD layer in
Perl. Writing one generic set of code,
programmers can leverage the power of
multiple databases and multiple
simultaneous database connections by
using this framework.
In order to utilize the libdbi
framework, you need to install drivers
for a particular type of database. The
drivers officially supported by libdbi
are split off into the libdbi-drivers
project. The current version of libdbi
(0.8.3) is supposed to work with any
0.8.x release of libdbi-drivers. Currently the following database
engines are supported:
* Firebird/Interbase
* FreeTDS (provides access to MS SQL Server and Sybase)
* MySQL
* PostgreSQL
* SQLite/SQLite3
|
1,289,167 | 1,289,198 | Template Polymorphism not Working? | I'm building a small template hierarchy and try to make use of class polymorphism. Here's some example code (which does not compile) to demonstrate it:
template<typename T>
struct A
{};
template<typename T>
struct B
{
B (A<B> *) {}
};
struct C : public B<int>
{
C(A<C> *p) : B<int>(p) {} // error
};
int main() {
A<C> ac;
C c(&ac);
}
My compiler (gcc 4.01 on OS X) throws the following error on the specified line:
error: no matching function for call to ‘B<int>::B(A<C>*&)’
But from my logical assumptions the code should work because
C == B<int>
B<int> == B<T>
=> A<C> == A<B<T> >
Can someone point out where my mistake lies and how to fix it, please?
EDIT
The answer seems to be that my problem can not be solved by regular inheritance trees because templates are to static to recognize polymorphism. Would it be legal then to cast A< C > to A< B < int > > to force polymorphism although it's horrible from a design standpoint?
struct C : public B<int>
{
C(A<C> *p) : B<int>((A<B<int> > *)p) {}
};
Is there any "good" solution for this problem?
| A < B < int > > is not the same type as A < C >, even if C is derived from B < int >.
So the parameter of constructor C, of type A < C >* is not compatible with the parameter requested of constructor B< int>, which is A < B < int> >.
Later edit:
Use templated constructors:
template<typename T>
struct B
{
template< typename E>
B (E *) {}
};
struct C : public B<int>
{
template< typename E>
C(E *p) : B<int>(p) {}
};
However, the problem is too abstract to give a solution...
|
1,289,172 | 1,289,277 | solving identifier "xxx" is undefined | I am experiencing something weird that I dont quite understand.
I am getting errors like:
framework/CP_STLArrayDefines.h(37): error: identifier "CP_String" is undefined
typedef std::vector<CP_String, std::allocator<CP_String> > CP_Strings_Array;
^
framework/CP_STLArrayDefines.h(37): error: identifier "CP_String" is undefined
typedef std::vector<CP_String, std::allocator<CP_String> >
But if I go look in CP_STLArrayDefines, I am clearly doing:
#include "CP_String.h"
if I go look at CP_String.h and .cpp they seem fine.
They are both in the same directory, etc.
What things should I look for?
Here is CP_STLArrayDefine.h:
#ifndef CP_STLArrayDefines_H
#define CP_STLArrayDefines_H
#ifndef TARGET_OS_LINUX
# pragma once
#endif
// CPLAT_Framework
#include "CP_Point.h"
#include "CP_String.h"
#include "CP_Types.h"
// Standard Library
#include <vector>
CPLAT_Begin_Namespace_CPLAT
// typedefs
#if ! TARGET_OS_LINUX
typedef std::vector`<CP_String, std::allocator<`CP_String>` >` CP_Strings_Array;
typedef std::vector`<CP_String, std::allocator<`CP_String>` >`::iterator CP_Strings_Iterator;
typedef std::vector`<CP_String, std::allocator<`CP_String>` >`::reverse_iterator CP_Strings_ReverseIterator;
| If you are certain that it's not a circular include then remember you can always fall back to that often overlooked technique of using the appropriate compiler switch to just dump out the preprocessed source i.e. have it stop before doing the compilation phase. Search through the output of that and you'll find out why the compiler's complaining as you're now looking at what the compiler sees.
The option is /E in MSVC and -E with gcc.
|
1,289,191 | 1,289,231 | How do you declare an extern "C" function pointer | So I have this code:
#include "boost_bind.h"
#include <math.h>
#include <vector>
#include <algorithm>
double foo(double num, double (*func)(double)) {
return 65.4;
}
int main(int argc, char** argv) {
std::vector<double> vec;
vec.push_back(5.0);
vec.push_back(6.0);
std::transform(vec.begin(), vec.end(), vec.begin(), boost::bind(foo, _1, log));
}
And receive this error:
return unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);
.............................................................^
%CXX-E-INCOMPATIBLEPRM, argument of type "double (* __ptr64 )(double) C" is
incompatible with parameter of type "double (* __ptr64 )(double)"
detected during:
instantiation of ...5 pages of boost
So this error is because 'log' is extern "C"'d in math.h
I was wondering how to declare my function pointer argument in foo() so it handles extern "C"'d functions.
| You can try including cmath instead, and using static_cast<double(*)(double)>(std::log) (cast necessary to resolve to the double overload).
Otherwise, you will limit your function to extern C functions. This would work like
extern "C" typedef double (*ExtCFuncPtr)(double);
double foo(double num, ExtCFuncPtr func) {
return 65.4;
}
Another way is to make foo a functor
struct foo {
typedef double result_type;
template<typename FuncPtr>
double operator()(double num, FuncPtr f) const {
return 65.4;
}
};
Then you can pass foo() to boost::bind, and because it's templated, it will accept any linkage. It will also work with function objects, not only with function pointers.
|
1,289,251 | 1,289,360 | Converting a UINT16 value into a UINT8 array[2] | This question is basically the second half to my other Question
How can I convert a UINT16 value, into a UINT8 * array without a loop and avoiding endian problems.
Basically I want to do something like this:
UINT16 value = 0xAAFF;
UINT8 array[2] = value;
The end result of this is to store value into a UINT8 array while avoiding endian conversion.
UINT8 * mArray;
memcpy(&mArray[someOffset],&array,2);
When I simply do memcpy with the UINT16 value, it converts to little-endian which ruins the output. I am trying to avoid using endian conversion functions, but think I may just be out of luck.
| How about
UINT16 value = 0xAAFF;
UINT8 array[2];
array[0]=value & 0xff;
array[1]=(value >> 8);
This should deliver the same result independent of endianness.
Or, if you want to use an array initializer:
UINT8 array[2]={ value & 0xff, value >> 8 };
(However, this is only possible if value is a constant.)
|
1,289,519 | 1,290,871 | Why aren't my CTreeCtrl checkboxes checking? | I've got a MFC CTreeCtrl stuck in a dialog with the TVS_CHECKBOXES style turned on. I get checkboxes next to all my tree items fine. In OnInitDialog I set the checked state of some of the items using CTreeCtrl::SetCheck but none of the items in the tree are checked when the tree is displayed. SetCheck is returning TRUE. Checking items with the mouse works fine. Anyone encounter this before?
| Figured out what the problems was. I was setting the TVS_CHECKBOXES style in the visual studio resource editor. Apparently this causes the problem I was having with the initial checks. Instead you have to do
m_nodeTree.ModifyStyle (TVS_CHECKBOXES, 0);
m_nodeTree.ModifyStyle (0, TVS_CHECKBOXES);
before filling the tree in OnInitDialog. Once I did this everything worked fine.
|
1,289,765 | 1,296,462 | Spell checker for comments, strings, maybe more | I am looking for a spell checker for c++ source code. Unfortunately all I can find is Visual Studio specific. I would like something which works on Linux.
Edit:
Ultimately I want to automate it in some way. I am not very proficient in spell checking, but what I am thinking of is a not-interactive console tool which prints error messages, or something like that.
Personally I use vim, but not everyone on the project does of course.
Currently we are using svn so it is possible to integrate it into the pre-commit-hook maybe?
Don't you guys do something similar?
| I found something!
svn co svn://anonsvn.kde.org/home/kde/trunk/quality/krazy2 krazy2
this is part of the quality management of KDE.
Besides a multitude of checks (KDE-specific, qt-specific, cpp-specific, ...) there is automated spell checking.
hope this helps
|
1,289,941 | 1,289,978 | Web Application Frameworks: C++ vs Python | I am familiar with both Python and C++ as a programmer. I was thinking of writing my own simple web application and I wanted to know which language would be more appropriate for server-side web development.
Some things I'm looking for:
It has to be intuitive. I recognize that Wt exists and it follows the model of Qt. The one thing I hate about Qt is that they encourage strange syntax through obfuscated means (e.g. the "public slots:" idiom). If I'm going to write C++, I need it to be standard, recognizable, clean code. No fancy shmancy silliness that Qt provides.
The less non-C++ or Python code I have to write, the better. The thing about Django (Python web framework) is that it requires you pretty much write the HTML by hand. I think it would be great if HTML forms took more of a wxWidgets approach. Wt is close to this but follows the Qt model instead of wxWidgets.
I'm typically writing video games with C++ and I have no experience in web development. I want to write a nice web site for many reasons. I want it to be a learning experience, I want it to be fun, and I want to easily be able to concentrate on "fun stuff" (e.g. less boilerplate, more meat of the app).
Any tips for a newbie web developer? I'm guessing web app frameworks are the way to go, but it's just a matter of picking one.
| If you'd like to avoid writing HTML, you could try GWT. However, in my experience, using an intermediate framework to generate HTML and ECMAScript never works anywhere near as well as hand-writing the pages.
[edit] nikow mentions in the comments that Pyjamas is a port of GWT to Python.
Regarding the language, if given the choice between C++ and Python I would pick Python 100% of the time. Even ignoring the obvious difference in abstraction between those languages, Python simply has more useful libraries than C++. You don't have to write your own development-oriented web server -- Django comes with one. You don't need to write a custom template library -- Python has Genshi. Django comes with a capable ORM layer, or for even more control you can use SQLAlchemy. It's barely a contest.
|
1,290,029 | 1,290,068 | How to Call a C++ Class Library From VB6 | How do I make a C++ class library COM-Visible, and call it from VB6 code?
| This is a very generic question. A lot depends on the complexity of the class you wish to expose and your familiarity with COM. If you're already using Visual Studio, then I'd suggest exploring ATL as the shortest path to happiness.
This article should help get you started.
http://msdn.microsoft.com/en-us/library/3ax346b7(VS.80).aspx
|
1,290,396 | 1,290,586 | How to make std::vector's operator[] compile doing bounds checking in DEBUG but not in RELEASE | I'm using Visual Studio 2008.
I'm aware that std::vector has bounds checking with the at() function and has undefined behaviour if you try to access something using the operator [] incorrectly (out of range).
I'm curious if it's possible to compile my program with the bounds checking. This way the operator[] would use the at() function and throw a std::out_of_range whenever something is out of bounds.
The release mode would be compiled without bounds checking for operator[], so the performance doesn't degrade.
I came into thinking about this because I'm migrating an app that was written using Borland C++ to Visual Studio and in a small part of the code I have this (with i=0, j=1):
v[i][j]; //v is a std::vector<std::vector<int> >
The size of the vector 'v' is [0][1] (so element 0 of the vector has only one element). This is undefined behaviour, I know, but Borland is returning 0 here, VS is crashing. I like the crash better than returning 0, so if I can get more 'crashes' by the std::out_of_range exception being thrown, the migration would be completed faster (so it would expose more bugs that Borland was hiding).
| Visual Studio 2005 and 2008 already do bounds-checking on operator[] by default, in both debug and release builds.
The macro to control this behavior is _SECURE_SCL. Set it to 0 to disable bounds-checking.
Their current plan in VS2010 is to disable bounds-checking by default in release builds, but keep it on in debug. (The macro is also getting renamed to _ITERATOR_DEBUG_LEVEL. I don't know if there's any formal documentation available on it yet, but it has been mentioned here and here)
|
1,290,404 | 1,290,429 | What are the WinXP console cursor control characters in c++? | I need the characters/escape sequences that move the console's cursor position. It would be nice to know the left/right/up/down cursor controls, but if that's not possible, a home (go to the first character of the first line in the console). Thanks in advance.
| There aren't any. The Windows console doesn't support such things.
See this Wikipedia article for more info.
However, if you just need to return to the beginning of the line, you can just emit a carriage return - try this:
#include <iostream>
using namespace std;
int main() {
cout << "foo" << "\r";
cout << "bar" << "\n";
}
It should display "bar" with no "foo".
|
1,290,517 | 1,290,528 | MessageBox returning 0 if HWND is bad | Is there a case where MessageBox can return 0 other than not enough memory? I have a case where I suspect the HWND I'm passing to MessageBox isn't valid or maybe it belongs to a window that is in the process of being destroyed.
In my case the MessageBox isn't displayed and returns 0, but I seem to have enough memory available.
|
Is there a case where MessageBox can return 0 other than not enough memory?
From the MSDN documentation:
http://msdn.microsoft.com/en-us/library/ms645505%28VS.85%29.aspx
If the function fails, the return value is zero. To get extended error information, call GetLastError.
I'd call GetLastError() to see what error code it returns.
|
1,290,706 | 1,292,097 | Apache C++ module persistent global objects | I want to keep some global objects in an Apache C++ module persistent across Apache child process invocations. How do I do this?
| You must use some form of storage external to the Apache processes.
Basic choices:
A database.
Shared memory (OS dependent).
Another process and use an IPC mechanism (eg. a socket)
A file.
Which one is appropriate depends on your requirements, and you might combine them. For example, "a database" is actually implemented as another process that makes things persistent in a file and it deals with concurrency issues in a known way.
In general, a database is probably the first thing to try and only go to other alternatives if you have specific issues that can be solved by taking a different approach.
|
1,291,111 | 1,292,102 | GCC / Linux: adding a static library to a .so? | I've a program that implements a plugin system by dynamically loading a function from some plugin_name.so (as usual).
But in turn I've a static "helper" library (lets call it helper.a) whose functions are used both from the main program and the main function in the plugin. They don't have to inter-operate in any way, they are just helper functions for text manipulation and such.
This program, once started, cannot be reloaded or restarted, that's why I'm expecting to have new "helper" functionality from the plugin, not from the main program.
So my questin is.. is it possible to force this "plugin function code" in the .so to use (statically link against?) a different (perhaps newer) version of "helper" than the main program?
How could this be done? perhaps by statically linking or otherwise adding helper.a to plugin_name.so?
| Nick Meyer's answer is correct on Windows and AIX, but is unlikely to be correct on every other UNIX platform by default.
On most UNIX platforms, the runtime loader maintains a single name space for all symbols, so if you define foo_helper in a.out, and also in plugin.so, and then call foo_helper from either, the first definition visible to the runtime loader (usually that from a.out) is used by default for both calls.
In addition, the picture is complicated by the fact that foo_helper may not be exported from a.out (and thus may be invisible to runtime loader), unless you use -rdynamic flag, or some other shared library references it. In other words, things may appear to work as Nick described them, then you add a shared library to the a.out link line, and they don't work that way anymore.
On ELF platforms (such as Linux), you have great control over symbol visibility and binding. See description of -fvisibility=hidden and -rdynamic in GCC man page, and also -Bsymbolic in linker man page.
Most other UNIX platforms have some way to control symbol bindings as well, but this is necessarily platform-specific.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.