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
|
|---|---|---|---|---|
479,816
| 479,888
|
networking lib + helper (c++)
|
Are there any c++ networking libs that are very useful and robust? and libs to help them be run better? something like automatically endian conversion when using <<, blocking reads until the struct or w/e your reading completely transfers, something to help debug your protocol, etc
|
Have you had a look at Boost.Asio? It's a networking library supporting both asynchronous and synchronous operation. I've made some experiments with it in the past, and found it quite useful.
|
479,919
| 480,146
|
Searching fast through a sorted list of strings in C++
|
I have a list of about a hundreds unique strings in C++, I need to check if a value exists in this list, but preferrably lightning fast.
I am currenly using a hash_set with std::strings (since I could not get it to work with const char*) like so:
stdext::hash_set<const std::string> _items;
_items.insert("LONG_NAME_A_WITH_SOMETHING");
_items.insert("LONG_NAME_A_WITH_SOMETHING_ELSE");
_items.insert("SHORTER_NAME");
_items.insert("SHORTER_NAME_SPECIAL");
stdext::hash_set<const std::string>::const_iterator it = _items.find( "SHORTER_NAME" ) );
if( it != _items.end() ) {
std::cout << "item exists" << std::endl;
}
Does anybody else have a good idea for a faster search method without building a complete hashtable myself?
The list is a fixed list of strings which will not change. It contains a list of names of elements which are affected by a certain bug and should be repaired on-the-fly when opened with a newer version.
I've built hashtables before using Aho-Corasick but I'm not really willing to add too much complexity.
I was amazed by the number of answers. I ended up testing a few methods for their performance and ended up using a combination of kirkus and Rob K.'s answers. I had tried a binary search before but I guess I had a small bug implementing it (how hard can it be...).
The results where shocking... I thought I had a fast implementation using a hash_set... well, ends out I did not. Here's some statistics (and the eventual code):
Random lookup of 5 existing keys and 1 non-existant key, 50.000 times
My original algorithm took on average 18,62 seconds
A lineair search took on average 2,49 seconds
A binary search took on average 0,92 seconds.
A search using a perfect hashtable generated by gperf took on average 0,51 seconds.
Here's the code I use now:
bool searchWithBinaryLookup(const std::string& strKey) {
static const char arrItems[][NUM_ITEMS] = { /* list of items */ };
/* Binary lookup */
int low, mid, high;
low = 0;
high = NUM_ITEMS;
while( low < high ) {
mid = (low + high) / 2;
if(arrAffectedSymbols[mid] > strKey) {
high = mid;
}
else if(arrAffectedSymbols[mid] < strKey) {
low = mid + 1;
}
else {
return true;
}
}
return false;
}
NOTE: This is Microsoft VC++ so I'm not using the std::hash_set from SGI.
I did some tests this morning using gperf as VardhanDotNet suggested and this is quite a bit faster indeed.
|
If your list of strings are fixed at compile time, use gperf
http://www.gnu.org/software/gperf/
QUOTE:
gperf is a perfect hash function generator. For a given list of strings, it produces a hash function and hash table, in form of C or C++ code, for looking up a value depending on the input string. The hash function is perfect, which means that the hash table has no collisions, and the hash table lookup needs a single string comparison only.
The output of gperf is not governed by gpl or lgpl, afaik.
|
480,211
| 480,232
|
When I need to specialize the typename I declared in my template class, what arguments I must use?
|
I have a template class for thread-safe vector:
template <class T>
class SharedVector {
std::vector<T> vect;
CRITICAL_SECTION cs;
SharedVector(const SharedVector<T>& rhs) {}
public:
typedef typename std::vector<T>::size_type SizeType;
SharedVector();
void PushBack(const T& value);
void PopBack();
SizeType size();
const T& operator[](int index);
void erase(int index);
void Lock();
void Unlock();
virtual ~SharedVector();
};
Then I want to use it in my client manager for TCP server to delegate some
responsibilities from client manager to this vector:
class TCPClientManager {
TCPClientManager(const TCPClientManager&) {}
TCPClientManager& operator=(const TCPClientManager&) {}
SharedVector<Connection*> connections;
public:
TCPClientManager();
SharedVector<>::SizeType size(); //here is the problem
void addConnection(const Client&);
void breakConnection(int);
void deleteConnection(int);
void Lock();
void Unlock();
~TCPClientManager();
};
typename SharedVector<>::SizeType TCPClientManager::size() {
return connections.size();
}
I need to declare the type of retrieving value. Compiler said that it was too few arguments for template.
|
You have to provide a type argument for the SharedVector template:
SharedVector<Connection*>::SizeType size();
....
SharedVector<Connection*>::SizeType TCPClientManager::size() {
return connections.size();
}
Because that Connection* type is not a template parameter in TCPClientManager, but an explicit chosen type, you don't need to put typename before SharedVector<Connection*>::SizeType
|
480,233
| 481,598
|
Are there any web frameworks for compiled languages like C++?
|
On our embedded device, we currently use PHP for its web interface, and unfortunately it's quite slow. We've been experimenting with Python, but is seems (at least on FPU-less ARM architecture) to be as slow as PHP.
Therefore we're thinking about implementing web interface in some compiled language like C++, but so far the only thing we've found is Wt, which looks more like desktop than web framework and it's documentation is rather complicated for a beginner.
So my question is: do you know about any good web frameworks for C/C++? What would make me totally happy would be something like C++ Django, but I doubt such thing exists :-)
|
If I were you, I would give Wt a try. I don't think you will find another solution as complete and easy to use as Wt with similar performance. The mailinglist are active, and has regular posts of people who use it on embedded devices. The Wiki (here) of the project mentions some numbers for embedded deployment and performance on ARM.
|
480,482
| 480,499
|
Linux/c++ log rotation scheme
|
I have a logger system which basically is a fancy way of writing my data to std::clog in a thread safe way.
I also, redirect std::clog to a file like this:
int main() {
std::ofstream logfile(config::logname, std::ios::app);
std::streambuf *const old_buffer = std::clog.rdbuf(logfile.rdbuf());
// .. the guts of the application
std::clog.rdbuf(old_buffer);
}
This works great... however, my application also produces a very large amount of logs. I was wondering what would be a good way to properly rotate my log files. Is there a safe way to switch out the file via a cron task? I would guess no.
The only thing I can think of that would definitely work is if I had the application itself open a new file, and redirect the rdbuf of clog to that while holding the logging mutex. But that feels like a cheap solution, and I would need to check so see if it is time to rotate logs fairly often for it to be effective. There has got to be a better way.
|
You can use the built-in log rotation method configured in /etc/logrotate.conf and/or /etc/logrotate.d/ - it's common to have logrotate send your app a SIGUSR1 as a signal to close and re-open all your log files.
|
480,525
| 483,942
|
Blocking read from FIFO via ifstream object
|
I open a FIFO file as ifstream. As soon as the object is created the thread is blocked until I send something into the FIFO (which is OK for me). Then I call getline() to get the data from the stream.
How do I read-block the thread again until more data is written into FIFO file?
Thanks
|
I haven't tested this code but I'm wondering if the FIFO is simply setting the EOF bit when you read all available data. In that case, you might be able to do this:
std::ifstream fifo;
std::string line;
bool done = false;
/* code to open your FIFO */
while (!done)
{
while (std::getline(fifo, line))
{
/* do stuff with line */
}
if (fifo.eof())
{
fifo.clear(); // Clear the EOF bit to enable further reading
}
else
{
done = true;
}
}
If you read off the end of the FIFO, reset and wait for further data. If an error occurred, you're done. I got the idea for this from this website. You might have to also close and reopen the FIFO in the same block where you do the reset.
|
481,119
| 481,291
|
Why does STL map core dump on find?
|
So, I have this situation where I need to see if an object is in my stl map. If it isn't, I am going to add it.
char symbolName[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
map<string,TheObject> theMap;
if (theMap.find(symbolName)==theMap.end()) {
TheObject theObject(symbolName);
theMap.insert(pair<string, TheObject>(symbolName,
theObject));
}
I am getting a core dump on the: theMap.find when the object is not already in the map.
Supposedly, if the item is not in the map, it is supposed to return an iterator equivelent to map::end
What is going on here?
GCC: 3.4.6
|
It can crash because of many reasons. Without knowing the definition of at least TheObject's constructors, i think we are largely left to guess at the problem. So far, your code looks fine, but it can be simplified:
char symbolName[] = "Hello";
map<string,TheObject> theMap;
theMap.insert(make_pair(symbolName, TheObject(symbolName)));
It won't do anything if the symbol is already mapped, discarding the new TheObject object.
|
481,196
| 481,382
|
How to detect if a base 10 decimal can be represented exactly in base 2
|
As part of a numerical library test I need to choose base 10 decimal numbers that can be represented exactly in base 2. How do you detect in C++ if a base 10 decimal number can be represented exactly in base 2?
My first guess is as follows:
bool canBeRepresentedInBase2(const double &pNumberInBase10)
{
//check if a number in base 10 can be represented exactly in base 2
//reference: http://en.wikipedia.org/wiki/Binary_numeral_system
bool funcResult = false;
int nbOfDoublings = 16*3;
double doubledNumber = pNumberInBase10;
for (int i = 0; i < nbOfDoublings ; i++)
{
doubledNumber = 2*doubledNumber;
double intPart;
double fracPart = modf(doubledNumber/2, &intPart);
if (fracPart == 0) //number can be represented exactly in base 2
{
funcResult = true;
break;
}
}
return funcResult;
}
I tested this function with the following values: -1.0/4.0, 0.0, 0.1, 0.2, 0.205, 1.0/3.0, 7.0/8.0, 1.0, 256.0/255.0, 1.02, 99.005. It returns true for -1.0/4.0, 0.0, 7.0/8.0, 1.0, 99.005 which is correct.
Any better ideas?
|
I think what you are looking for is a number which has a fractional portion which is the sum of a sequence of negative powers of 2 (aka: 1 over a power of 2). I believe this should always be able to be represented exactly in IEEE floats/doubles.
For example:
0.375 = (1/4 + 1/8) which should have an exact representation.
If you want to generate these. You could try do something like this:
#include <iostream>
#include <cstdlib>
int main() {
srand(time(0));
double value = 0.0;
for(int i = 1; i < 256; i *= 2) {
// doesn't matter, some random probability of including this
// fraction in our sequence..
if((rand() % 3) == 0) {
value += (1.0 / static_cast<double>(i));
}
}
std::cout << value << std::endl;
}
EDIT: I believe your function has a broken interface. It would be better if you had this:
bool canBeRepresentedExactly(int numerator, int denominator);
because not all fractions have exact representations, but the moment you shove it into a double, you've chosen a representation in binary... defeating the purpose of the test.
|
482,073
| 482,091
|
Make a copy of an unknown concrete type in c++
|
Suppose we have the following class hierarchy:
class Base {
...
};
class Derived1 : public Base {
...
};
class Derived2 : public Base {
...
};
Given a Base* which could point to either a Derived1 or Derived2 object how can I make a copy of the actual object given that it's concrete type is unknown. I thought of defining copy constructors but I don't think this is possible without knowing the actual types involved. The only solution I can think of is defining a clone() method on each type in the hierarchy. Can anybody think of something more elegant?
|
Unfortunately a virtual clone/copy pattern is your only real choice.
There are variations of this, but essentially they all come down to writing functions for each type that can return a new copy.
|
482,315
| 482,323
|
How do you check for an invalid pointer?
|
My current code to the effect of:
if( objectPointer != NULL){
delete objectPointer;
}
doesn't work because the pointers are getting set to invalid hex numbers by the compiler such as:
0xbaadf00d
0xdeadbeef
etc....
So what's the best way to check for an invalid pointer before trying to delete the object?
|
Always initialize your pointers to NULL (that is, 0). From http://www.lysator.liu.se/c/c-faq/c-1.html:
A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere.
|
482,726
| 482,737
|
signal when user kills process?
|
I overloaded the 6 signals listed on this site http://www.cplusplus.com/reference/clibrary/csignal/signal.html
Then i ran my app (double click not ran through IDE) and tried 1) end task 2) X on topright and 3) kill process. I expected the first two to cause some kind of signal (i am on XP) but alas i got nothing. Am i not allowed to open files to write into when a signal occurs? i am guessing i am (SIGSEGV allowed me).
When firefox crashes or when i kill it, it remembers what pages i was. Does it log the address everytime i click a page or does it do that on a signal/crash?
my main question is what signal can i use to catch kill process
|
Win32 does not provide an option to intercept your program being killed with TerminateProcess (which is what will happen when you "End Task" from Task Manager or click on the [X]).
You can catch the SIGSEGV signal because the C runtime library provides an emulation of this signal when running on Windows. When your program causes a Windows access violation (exception 0xC0000005), the runtime library has the option to catch that and simulate a Unix style SIGSEGV for you. This is, however, not the best way to handle such an exception. If you are writing a Win32 program, you shouldn't generally try to use Unix style services.
|
482,745
| 484,304
|
namespaces for enum types - best practices
|
Often, one needs several enumerated types together. Sometimes, one has a name clash. Two solutions to this come to mind: use a namespace, or use 'larger' enum element names. Still, the namespace solution has two possible implementations: a dummy class with nested enum, or a full blown namespace.
I'm looking for pros and cons of all three approaches.
Example:
// oft seen hand-crafted name clash solution
enum eColors { cRed, cColorBlue, cGreen, cYellow, cColorsEnd };
enum eFeelings { cAngry, cFeelingBlue, cHappy, cFeelingsEnd };
void setPenColor( const eColors c ) {
switch (c) {
default: assert(false);
break; case cRed: //...
break; case cColorBlue: //...
//...
}
}
// (ab)using a class as a namespace
class Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
class Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
void setPenColor( const Colors::e c ) {
switch (c) {
default: assert(false);
break; case Colors::cRed: //...
break; case Colors::cBlue: //...
//...
}
}
// a real namespace?
namespace Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
namespace Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
void setPenColor( const Colors::e c ) {
switch (c) {
default: assert(false);
break; case Colors::cRed: //...
break; case Colors::cBlue: //...
//...
}
}
|
Original C++03 answer:
The benefit from a namespace (over a class) is that you can use using declarations when you want.
The problem with using a namespace is that namespaces can be expanded elsewhere in the code. In a large project, you would not be guaranteed that two distinct enums don't both think they are called eFeelings
For simpler-looking code, I use a struct, as you presumably want the contents to be public.
If you're doing any of these practices, you are ahead of the curve and probably don't need to scrutinize this further.
Newer, C++11 advice:
If you are using C++11 or later, enum class will implicitly scope the enum values within the enum's name.
With enum class you will lose implicit conversions and comparisons to integer types, but in practice that may help you discover ambiguous or buggy code.
|
482,798
| 482,825
|
Accessing a subset (not subtree) of an object hierarchy
|
I have a base class "Node" which contains a list of child nodes. Node defines a "forEachNode" function which takes a callback as a parameter and calls it on each node in the hierarchy.
I have a class derived from Node - "SpecialNode" (not really a name I'd choose - just an example!). Node knows nothing about SpecialNode.
I want to iterate over just the SpecialNodes. I've got to the point where SpecialNode defines a callback to pass to "forEachNode", but I'm not sure how to call the callback for SpecailNodes only. Any advice?
|
You can try something like:
if (dynamic_cast<SpecialNode*>(n) != NULL) {
do_something();
}
Or you put a virtual function in Node in order to be called from the callback which you can implement differently in the subclasses.
|
482,955
| 482,977
|
Why was constness removed from Java and C#?
|
I know this has been discussed many times, but I am not sure I really understand why Java and C# designers chose to omit this feature from these languages. I am not interested in how I can make workarounds (using interfaces, cloning, or any other alternative), but rather in the rationale behind the decision.
From a language design perspective, why has this feature been declined?
P.S: I'm using words such as "omitted", which some people may find inadequate, as C# was designed in an additive (rather than subtractive) approach. However, I am using such words because the feature existed in C++ before these languages were designed, so it is omitted in the sense of being removed from a programmer's toolbox.
|
In this interview, Anders said:
Anders Hejlsberg: Yes. With respect to
const, it's interesting, because we
hear that complaint all the time too:
"Why don't you have const?" Implicit
in the question is, "Why don't you
have const that is enforced by the
runtime?" That's really what people
are asking, although they don't come
out and say it that way.
The reason that const works in C++ is
because you can cast it away. If you
couldn't cast it away, then your world
would suck. If you declare a method
that takes a const Bla, you could pass
it a non-const Bla. But if it's the
other way around you can't. If you
declare a method that takes a
non-const Bla, you can't pass it a
const Bla. So now you're stuck. So you
gradually need a const version of
everything that isn't const, and you
end up with a shadow world. In C++ you
get away with it, because as with
anything in C++ it is purely optional
whether you want this check or not.
You can just whack the constness away
if you don't like it.
|
483,031
| 483,052
|
Best way to get a query result
|
I'm developing an application that gets large images from an Internet server which is the best way to download this images, without freeze the entire application? I mean background download. I have thought about download it in another thread.
|
Yes, you need to spawn another thread to do the network communication, and then when it is finished doing it's reading, you can use a volatile boolean flag to indicate that the work is complete and the main/application thread can take the data and incorporate it. The data may be "part" of an image if you want to show the image coming in piece by piece (as a browser does).
|
483,136
| 566,463
|
Split a varbinary in a SELECT
|
I have a large varbinary field in one of my tables, and I would like to download in parts for show a download progress indicator in my application.
How can I split the data sent in a SELECT query?
Thanks
|
You can do this with just the SQLGetData ODBC call. If the buffer size you provide is smaller than the total varbinary size, it will fill the buffer and return SQL_SUCCESS_WITH_INFO and and SQLSTATE 01004. If you call it again, it will return the next segment of data. You just repeat until all the data is retrieved. To know your progress as a percentage, you may be able to select the length as another column.
See here for lots of tips for getting long data.
|
483,164
| 483,286
|
Looking for benchmarking code snippet (c++)
|
Some loading routines in my program takes to long to complete. I want a quick small snippet for checking how long a function took to execute. By small I mean "preferably without 3rd party libraries".
Maybe something as simple as taking the system time?
start = current_system_time()
load_something()
delta = current_system_time()-start
log_debug("load took "+delta)
Edit: Target OS in question is Windows.
|
Your answer: Yes
Caveat: That WON'T work in multihtreaded code or multiple core machines, you need a robust wall-clock timer.
So I recommend you use omp's wallclock. OMP is included with VC and GCC, and most compilers and its a standard you don't need to worry about disappearing
#include <omp.h>
// Starting the time measurement
double start = omp_get_wtime();
// Computations to be measured
...
// Measuring the elapsed time
double end = omp_get_wtime();
// Time calculation (in seconds)
|
483,276
| 483,314
|
How to prevent crashing if com dll isnt registered
|
From some old c++ code im trying to use a com dll, it works fine when the dll is registered, but it crahses if the dll isnt registered.
// Initialize COM.
HRESULT hr = CoInitialize(NULL);
IGetTestPtr ptest(__uuidof(tester));
"Use method from the dll"
// Uninitialize COM.
CoUninitialize();
Is it anyway to check if the dll has been registered, before calling IGetTestPtr ptest(__uuidof(tester))?
Or what is the correct way to prevent the crash?
|
Calling CreateInstance on your object will return an HRESULT that can be tested for success:
IGetTestPtr p = null;
HRESULT hRes = p.CreateInstance( __uuidof(tester) );
bool bSuccess = SUCCEEDED(hRes);
This assumes you've created an interface wrapper around your type library using Visual Studio, where COM Smart Pointers are used in the interface (this gives you the CreateInstance method).
|
483,609
| 483,653
|
How can I convert hexadecimal numbers to binary in C++?
|
I am taking a beginning C++ class, and would like to convert letters between hex representations and binary. I can manage to print out the hex numbers using:
for(char c = 'a'; c <= 'z'; c++){
cout << hex << (int)c;
}
But I can't do the same for binary. There is no std::bin that I can use to convert the decimal numbers to binary.
|
Like so:
for(char c = 'a'; c <= 'z'; c++){
std::bitset<sizeof(char) * CHAR_BIT> binary(c); //sizeof() returns bytes, not bits!
std::cout << "Letter: " << c << "\t";
std::cout << "Hex: " << std::hex << (int)c << "\t";
std::cout << "Binary: " << binary << std::endl;
}
|
483,652
| 483,765
|
XA distributed transactions in C++
|
Is there a good C++ framework to implement XA distributed transactions?
With the term "good" I mean usable, simple (doesn't imply "easy"), well-structured.
Due to study reasons, at the moment I'm proceeding with a personal implementation, following X/Open XA specification.
Thank you in advance.
|
I am not aware of an open-source or free transaction monitor that has any degree of maturity, although This link does have some fan-out. The incumbent commercial ones are BEA's Tuxedo, Tibco's Enterprise Message Service (really a transactional message queue manager like IBM's MQ) and Transarc's Encina (now owned by IBM). These systems are all very expensive.
If you want to make your own (and incidentally make a bit of a name for yourself by filling a void in the open-source software space) get a copy of Grey and Reuter.
This is the definitive work on transaction processing systems architecture, written by two of the foremost experts in the field.
Interestingly, they claim that one can implement a working TP monitor in around 10,000 lines of C. This actually sounds quite reasonable, as what it does is not all that complex. On occasion I have been tempted to try.
Essentially you need to make a distributed transaction coordinator that runs as a daemon process. You will need to get the resource manager protocol working from it, so starting with this as a prototype is probably a good start. If you can get it to independently roll back or commit a transaction you have the basis of the TM-RM interface.
The XA API as defined in the spec is the API to control the transaction manager. Strictly speaking, you don't need to make a 3-tier architecture to use distributed transactions of this sort, but they are more or less pointless without a TP monitor. How you communicate from the front-end to the middle-tier can be left as an exercise for the reader. You are probably best off using an existing ORB, of which there are several good open-source implementations available.
Depending on whether you want to make the DTC and the app server separate processes (which is possibly desirable for stability but not strictly necessary) you could also use ACE as a basis for the DTC server.
If you want to make a high-performance middle-tier server, check out Douglas Schmidt's ACE framework. This comes with an ORB called TAO, and is flexible enough to allow you to use more or less any threading model that takes your fancy. Using this is a trade-off between learning it and the effort of writing your own and debugging all the synchronisation and concurrancy issues.
|
483,797
| 483,887
|
Dynamic Shared Library compilation with g++
|
I'm trying to compile the following simple DL library example code from Program-Library-HOWTO with g++. This is just an example so I can learn how to use and write shared libraries. The real code for the library I'm developing will be written in C++.
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen ("/lib/libm.so.6", RTLD_LAZY);
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
cosine = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
printf ("%f\n", (*cosine)(2.0));
dlclose(handle);
}
If I compile the program with gcc it works fine.
gcc -o foo foo.c -ldl
When I change the filename and compiler to the following
g++ -o foo foo.cpp -ldl
I get the following error:
foo.cpp:16: error: invalid conversion from 'void*' to 'double (*)(double)'
I understand (I think I understand, correct me if this is wrong) that I can't do an implicit cast from a void pointer in C++, but C lets me, and this is why the above code will compile using gcc but not using g++. So I tried an explicit cast by changing line 16 above to:
cosine = (double *)dlsym(handle, "cos");
With this in place, I get the following error:
foo.cpp:16: error: cannot convert 'double*' to 'double (*)(double)' in assignment
These problems probably have more to do with my own general ignorance of proper C++ coding standards than anything else. Can anyone point me to a good tutorial on developing dynamic libraries for Linux that uses C++ example code?
|
C allows implicit casts from void * to any pointer type (including function pointers); C++ requires explicit casting. As leiflundgren says, you need to cast the return value of dlsym() to the function pointer type you need.
Many people find C's function pointer syntax awkward. One common pattern is to typedef the function pointer:
typedef double (*cosine_func_ptr)(double);
You can define your function pointer variable cosine as a member of your type:
cosine_func_ptr cosine;
And cast using the type instead of the awkward function pointer syntax:
cosine = (cosine_func_ptr)dlsym(handle, "cos");
|
483,919
| 483,965
|
CTreeCtrl - getting an item position
|
Is there a way of getting the position (index) of an item in a CTreeCtrl?
I am interested in the index of a node at its particular level.
I was thinking to maintain the item positions within the item "data" field, but the problem is that my tree is sorted and I cannot predict the position an item will receive (well, only if I sort the items in advance which I would like to avoid).
|
I don't think you can. I assumed that maybe the control could be treated as an array (maybe it still can but I can't find a reference).
Anyways, there are no member functions (according to the MFC API) that give you access to that information
|
483,971
| 484,149
|
Why is my ReadDirectoryChangesW not picking up changed files?
|
I'm sure I am just doing something really dumb and not seeing it but can anyone tell me why the following code would not be picking up changes in the passed in directory?
When calling this code, creating and modifying files or directories in the passed in m_directory is ignored. But if I call
PostQueuedCompletionStatus( m_hCompletionPort, 0, 0, NULL );
then GetQueuedCompletionStatus correctly exits. Does anyone see what I am doing wrong? Here is the code:
// create handle to log dir
HANDLE logDirHandle = CreateFile(m_directory,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS |
FILE_FLAG_OVERLAPPED,
NULL);
// create the completion port
m_hCompletionPort = CreateIoCompletionPort(logDirHandle, NULL, 0, 1);
// initial registration for changes
DWORD dwBufLength;
FILE_NOTIFY_INFORMATION notifyInfo;
OVERLAPPED overlapped;
ReadDirectoryChangesW(logDirHandle,
¬ifyInfo,
MAX_BUFFER,
TRUE,
FILE_NOTIFY_CHANGE_LAST_WRITE|FILE_NOTIFY_CHANGE_CREATION,
&dwBufLength,
&overlapped,
NULL);
// wait for a change
LPOVERLAPPED lpOverLapped;
ULONG key;
DWORD numBytes;
GetQueuedCompletionStatus(m_hCompletionPort, &numBytes, &key, &lpOverLapped, INFINITE))
EDIT:
Ok, I thought for sure ReadDirectoryChangesW() was returning TRUE but it is not. GetLastError() tells me the error is ERROR_INVALID_HANDLE (6). The strange thing is that logDirHandle appears to be valid and no error occurred in the call to CreateFile().
Also I refactored slightly to call the synchronous ReadDirectoryChangesW keeping everything the same except losing the OVERLAPPED stuff and it worked fine. So I am guessing I am implementing the OVERLAPPED stuff incorrectly?
|
Did you check the return values? And is this over a network?
Edit: You probably want to initialize OVERLAPPED to zero.
|
484,142
| 495,448
|
How can you make an MFC application with an HTML view consistently accept drag-dropped files?
|
I'm trying to decipher CHtmlView's behaviour when files are dragged into the client area, so I've created a new MFC app and commented out the CHtmlView line that navigates to MSDN on startup. In my main frame, I've overridden CWnd::OnDropFiles() with a function that shows a message box, to see when WM_DROPFILES is sent.
OnDropFiles() gets triggered on all except the first time you try to drag a file into the application. Uniquely, that first time appears to be interpreted by the application as a request to display the data in the file rather than a request to open the file. I've tried overriding OnDrop() from the view class, but it's never called.
Why is the first time different? How can I catch all attempts to drag a file into my app?
|
This is part of the underlying WebBrowser control behaviour. CHtmlView sets RegisterAsDropTarget to true by default, which means the control intercepts the drop operation and performs its own processing.
If you want to inhibit it, call SetRegisterAsDropTarget(FALSE) in your OnInitialUpdate implementation. All drop operations will then interact with the main window.
|
484,172
| 484,551
|
Do we need a Java++?
|
It seems to me that, in some ways, Java is where C was a while back. Both are fairly minimalist languages for their time, with relatively clean, simple cores to build on. (I'm referring to the core language here, not the libraries.) Both are/were extremely popular. Both are/were lingua francas, with tons of legacy code. Both are/were lacking several modern productivity features that programmers from other languages often miss. Both seem very inertia-dominated and slow to adapt to a changing world.
It seems to me like it would be reasonable to create a Java++ that's roughly a superset of of Java, as C++ is to C. Such a language would attempt to lift Java out of the relative stagnation it's undergone, break backwards compatibility only in a few minor ways only if absolutely necessary, add lots of modern features that plain old Java is missing, and worry about standardization later. Features that might be a good idea include:
First class functions, delegates.
Closures.
Static type inference, similar to var in C# or auto in D.
Operator overloading.
Structs as value types distinct from classes, like C# and D.
Properties.
An option to ignore checked exceptions.
The ability to declare more than one top-level public class in a file.
More powerful builtin arrays that allow things like appending.
Better generics/real templates.
Something like the dynamic keyword for C# 4.0 that allows duck typing when necessary in a generally static language.
Since Java is primarily a VM language, maybe some hardcore metaprogramming features like generating code on the fly for certain things.
Do you think there would be demand for such a language? Do you think such a thing would succeed?
Edit: I'm not talking about compatibility at the runtime/bytecode level, I'm talking about compatibility w/ Java at the source level. Also, yes, Java 7 could add some of these, but it seems like the "official" process for adding features to Java is extremely conservative. The real point is the idea of forking Java into a branch were the focus is on innovation more than stability/standardization.
|
Going to get downvoted by the Java fanboys for this but as someone who writes both Java and C# I'd say that C# is as close to Java ++ as you are going to get.
C to C++ was a paradigm shift, from procedural to Object oriented, the only reason they retain the name is to woo C programmers into thinking that it was the same language which led to a load of really bad C code masquerading as C++.
Java is constantly expanding and Sun are quickly incorporating more and more features, so it could well be that Java 7 or 8 is your Java ++
|
484,213
| 484,386
|
Replace line breaks in a STL string
|
How can I replace \r\n in an std::string?
|
Use this :
while ( str.find ("\r\n") != string::npos )
{
str.erase ( str.find ("\r\n"), 2 );
}
more efficient form is :
string::size_type pos = 0; // Must initialize
while ( ( pos = str.find ("\r\n",pos) ) != string::npos )
{
str.erase ( pos, 2 );
}
|
484,466
| 484,686
|
Best way to create a timer on screen
|
I had this idea of creating a count down timer, like 01:02, on the screen (fullsize).
One thing is that I really don't have a clue on how to start.
I do know basic c/c++, win32 api and a bit of gdi.
Anyone have any pointers on how to start this? My program would be like making the computer into a big stopwatch (but with added features)
Not asking for code, just some ideas/primers on how to start this.
Doing mostly web stuff has made me a bit rusty in win programming.
Any ideas are welcomed
Thanks
Note: I think I have to do this with c/c++ because of speed. My stopwatch program would run in a very slow pc, something like a p3 800mhz, so speed is really important.
|
If you have some experience with windows message processing and the Win32 API, this should get you started.
LRESULT WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT r;
char szBuffer[200];
static int count = 120;
int seconds = 0;
int minutes = 0;
int hours = 0;
switch (message) {
case WM_CREATE:
// create a 1 second timer
SetTimer (hwnd, ID_TIMER, 1000, NULL);
return 0;
case WM_PAINT:
if(count > 0)
{
hdc = BeginPaint (hwnd, &ps);
GetClientRect (hwnd, &r);
hours = count / 3600;
minutes = (count / 60) % 60;
seconds = count % 60;
wsprintf (szBuffer, "Hours: %d Minutes: %d Seconds: %d", hours, minutes, seconds);
DrawText (hdc, szBuffer, -1, &r, DT_LEFT);
EndPaint (hwnd, &ps);
}
else
{
SendMessage (hwnd, WM_CLOSE, 0, 0L)
}
return 0;
case WM_TIMER:
count--;
InvalidateRect (hwnd, NULL, TRUE);
return 0;
case WM_DESTROY:
KillTimer (hwnd, ID_TIMER);
PostQuitMessage (0);
return 0;
} /* end switch */
}
Here's a good link on using timers:
Using Timers
|
484,592
| 484,736
|
Overriding public virtual functions with private functions in C++
|
Is there is any reason to make the permissions on an overridden C++ virtual function different from the base class? Is there any danger in doing so?
For example:
class base {
public:
virtual int foo(double) = 0;
}
class child : public base {
private:
virtual int foo(double);
}
The C++ faq says that it is a bad idea, but doesn't say why.
I have seen this idiom in some code and I believe that the author was attempting to make the class final, based on an assumption that it is not possible to override a private member function. However, This article shows an example of overriding private functions. Of course another part of the C++ faq recommends against doing so.
My concrete questions:
Is there any technical problem with using a different permission for virtual methods in derived classes vs base class?
Is there any legitimate reason to do so?
|
The problem is that the Base class methods are its way of declaring its interface. It is, in essence saying, "These are the things you can do to objects of this class."
When in a Derived class you make something the Base had declared as public private, you are taking something away. Now, even though a Derived object "is-a" Base object, something that you should be able to do to a Base class object you cannot do to a Derived class object, breaking the Liskov Substitution Prinicple
Will this cause a "technical" problem in your program? Maybe not. But it will probably mean object of your classes won't behave in a way your users expect them to behave.
If you find yourself in the situation where this is what you want (except in the case of a deprecated method referred to in another answer), chances are you have an inheritance model where inheritance isn't really modeling "is-a," (e.g. Scott Myers's example Square inheriting from Rectangle, but you can't change a Square's width independent of its height like you can for a rectangle) and you may need to reconsider your class relationships.
|
484,707
| 489,073
|
Viewing a dynamically-allocated array with the Xcode debugger?
|
Let's say I have an array in C++:
double* velocity = new double[100];
Using the GDB command line, I can view this array with the command:
> print *velocity @ 100
and it will print a nicely-formatted list of all the double values inside the array.
However, when using the Xcode debugger, the most it will do is treat this as a pointer to a single double value, and display velocity[0] in the variable list.
This makes it a real PITA to debug programs that contain large dynamically allocated array. There has got to be some way to tell Xcode "This is a pointer to an array of length 100", and have it display the thing as such. Anyone know what it is?
|
You can use gdb syntax as expressions:
Use Run/Show/Expressions... menu to show the expressions window
Enter '*velocity @ 100' at the bottom of the window (Expression:)
|
484,758
| 484,779
|
unable to pass a pointer to a function between classes
|
I'm attempting to pass a pointer to a function that is defined in one class into another class. After much research, I believe my syntax is correct, but I am still getting compiler errors. Here is some code which demonstrates my issue:
class Base
{
public:
BaseClass();
virtual ~BaseClass();
};
class Derived : public Base
{
public:
// assign strFunction to the function pointer passed in
Derived(string (*funPtr)(int)) : strFunction(funPtr);
~Derived();
private:
// pointer to the function that is passed in
string (*strFunction)(int value);
};
class MainClass
{
public:
MainClass()
{
// allocate a new Derived class and pass it a pointer to myFunction
Base* myClass = new Derived(&MainClass::myFunction);
}
string myFunction(int value)
{
// return a string
}
};
When I try to compile this code, the error I get is
error: no matching function for call to 'Derived::Derived(string (MainClass::*)(int))'
followed by
note: candidates are: Derived::Derived(string (*)(int))
Any idea what I might be doing wrong?
|
your syntax is correct for a C style function pointer. Change it to this:
Derived(string (MainClass::*funPtr)(int)) : strFunction(funPtr) {}
and
string (MainClass::*strFunction)(int value);
remember to call strFunction, you will need an instance of a MainClass object. Often I find it useful to use typedefs.
typedef string (MainClass::*func_t)(int);
func_t strFunction;
and
Derived(func_t funPtr) : strFunction(funPtr) {}
|
484,853
| 484,867
|
Levenshtein algorithm: How do I meet this text editing requirements?
|
I'm using levenshtein algorithm to meet these requirements:
When finding a word of N characters, the words to suggest as correction in my dictionary database are:
Every dictionary word of N characters that has 1 character of difference with the found word.
Example:
found word:bearn, dictionary word: bears
Every dictionary word of N+1 characters that has N characters equal to the found word.
Example:
found word:bear, dictionary word: bears
Every dictionary word of N-1 characters that has N-1 characters equal to the found word.
Example:
found word: bears, dictionary word: bear
I'm using this implementation of Levenshtein algorithm in C++ to find when a word has a Levenshtein number of 1 (which is the Levenshtein number for all three cases), but then how do I choose the word to suggest? I read about Boyer-Moore-Horspool and Knuth-Morris-Pratt but I'm not sure on how either of them can be helpful.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int levenshtein(const string &s1, const string &s2)
{
string::size_type N1 = s1.length();
string::size_type N2 = s2.length();
string::size_type i, j;
vector<int> T(N2+1);
for ( i = 0; i <= N2; i++ )
T[i] = i;
for ( i = 0; i < N1; i++ ) {
T[0] = i+1;
int corner = i;
for ( j = 0; j < N2; j++ ) {
int upper = T[j+1];
if ( s1[i] == s2[j] )
T[j+1] = corner;
else
T[j+1] = min(T[j], min(upper, corner)) + 1;
corner = upper;
}
}
return T[N2];
}
|
You may also want to add Norvig's excellent article on spelling correction to your reading.
It's been a while since I've read it but I remember it being very similar to what your writing about.
|
484,882
| 484,915
|
What OOP design decision will suit the situation of protocol in client/server app?
|
I am writing a client/server app in C++ and need to realize simple protocol to sent and receive data correctly. I have a class for server protocol which can convert the message to my format and then convert it again from this format.
That what is server-side protocol looks like:
class BaseProtocol {
protected:
int NumberOfBytesInPackOfText;
std::string serviceString;
public:
BaseProtocol(int SizeOfTextPack, const char* extraString):
NumberOfBytesInPackOfText(SizeOfTextPack),
serviceString(extraString) {}
virtual std::string& convertToSystemMessage(const char* message)=0;
virtual std::string& convertToNativeMessage(const char* message)=0;
virtual ~BaseProtocol() {
NumberOfBytesInPackOfText = 0;
serviceString = "";
}
};
class SimpleProtocol: public BaseProtocol {
public:
SimpleProtocol(int SizeOfTextPack, const char* service):
BaseProtocol(SizeOfTextPack, service) {}
std::string& convertToSystemMessage(const char* nativeMessage);
std::string& convertToNativeMessage(const char* systemMessage);
};
Now I can not decide what will be the better decision to make to implement that protocol on client application. A friend class to the server protocol? Or may be I need to extract subclass from server protocol and then the client protocol will be derived from this class?
|
I would create a protocol class independent of both the client and the server. They can each call the functions of that class rather than inheriting from the class.
This follows the principle of favoring composition over inheritance. Also, neither the client nor the server "is a" protocol interpreter. Rather, they each simply need to use the protocol.
|
485,155
| 485,271
|
C/C++ Performance Globals vs Get/Set Methods
|
I saw this question asking about whether globals are bad.
As I thought about the ramifications of it, the only argument I could come up with that they're necessary in some cases might be for performance reasons.
But, I'm not really sure about that. So my question is, would using a global be faster than using a get/set method call?
|
A more appropriate comparison would be between accessing a global (a static) and a local.
Indeed a global is faster because accessing a local requires the variable offset to be added to the value of the stack pointer.
However, you will never, ever need to worry about this. Try concentrating on things that matter, such as making your code be readable, writable, and working.
|
485,230
| 485,251
|
C++ Tokenizing using iterators in an eof() cycle
|
I'm trying to adapt this answer
How do I tokenize a string in C++?
to my current string problem which involves reading from a file till eof.
from this source file:
Fix grammatical or spelling errors
Clarify meaning without changing it
Correct minor mistakes
I want to create a vector with all the tokenized words. Example: vector<string> allTheText[0] should be "Fix"
I don't understad the purpose of istream_iterator<std::string> end; but I included cause it was on the original poster's answer.
So far, I've got this non-working code:
vector<string> allTheText;
stringstream strstr;
istream_iterator<std::string> end;
istream_iterator<std::string> it(strstr);
while (!streamOfText.eof()){
getline (streamOfText, readTextLine);
cout<<readTextLine<<endl;
stringstream strstr(readTextLine);
// how should I initialize the iterators it and end here?
}
Edit:
I changed the code to
vector<string> allTheText;
stringstream strstr;
istream_iterator<std::string> end;
istream_iterator<std::string> it(strstr);
while (getline(streamOfText, readTextLine)) {
cout << readTextLine << endl;
vector<string> vec((istream_iterator<string>(streamOfText)), istream_iterator<string>()); // generates RuntimeError
}
And got a RuntimeError, why?
|
Using a while (!….eof()) loop in C++ is broken because the loop will never be exited when the stream goes into an error state!
Rather, you should test the stream's state directly. Adapted to your code, this could look like this:
while (getline(streamOfText, readTextLine)) {
cout << readTextLine << endl;
}
However, you already have a stream. Why put it into a string stream as well? Or do you need to do this line by line for any reason?
You can directly initialize your vector with the input iterators. No need to build a string stream, and no need to use the copy algorithm either because there's an appropriate constructor overload.
vector<string> vec((istream_iterator<string>(cin)), istream_iterator<string>());
Notice the extra parentheses around the first argument which are necessary to disambiguate this from a function declaration.
EDIT A small explanation what this code does:
C++ offers a unified way of specifying ranges. A range is just a collection of typed values, without going into details about how these values are stored. In C++, these ranges are denoted as half-open intervals [a, b[. That means that a range is delimited by two iterators (which are kind of like pointers but more general; pointers are a special kind of iterator). The first iterator, a, points to the first element of the range. The second, b, points behind the last element. Why behind? Because this allows to iterate over the elements very easily:
for (Iterator i = a; i != b; ++i)
cout << *i;
Like pointers, iterators are dereferenced by applying * to them. This returns their value.
Container classes in C++ (e.g. vector, list) have a special constructor which allows easy copying of values from another range into the new container. Consequently, this constructor expects two iterators. For example, the following copies the C-style array into the vector:
int values[3] = { 1, 2, 3 };
vector<int> v(values, values + 3);
Here, values is synonymous with &values[0] which means that it points to the array's first element. values + 3, thanks to pointer arithmetic, is nearly equivalent to &values[3] (but this is invalid C++!) and points to the virtual element behind the array.
Now, my code above does the exact same as in this last example. The only difference is the type of iterator I use. Instead of using a plain pointer, I use a special iterator class that C++ provides. This iterator class wraps an input stream in such a way that ++ advances the input stream and * reads the next element from the stream. The kind of element is specified by the type argument (hence string in this case).
To make this work as a range, we need to specify a beginning and an end. Alas, we don't know the end of the input (this is logical, since the end of the stream may actually move over time as the user enters more input into a console!). Therefore, to create a virtual end iterator, we pass no argument to the constructor of istream_iterator. Conversely, to create a begin iterator, we pass an input stream. This then creates an iterator that points to the current position in the stream (here, cin).
My above code is functionally equivalent to the following:
istream_iterator<string> front(cin);
istream_iterator<string> back;
vector<string> vec;
for (istream_iterator<string> i = front; i != back; ++i)
vec.push_back(*i);
and this, in turn, is equivalent to using the following loop:
string word;
while (cin >> word)
vec.push_back(word);
|
485,358
| 485,434
|
Why did I get a Segmentation Fault with a map insert
|
I want to insert a pair< string, vector<float> > into a map, first it works, but after several loops, it cannot insert any more and throw me a segmentation fault. Can anybody give a possible reason?
Btw: I first read a file and generate the map (about 200,000 elements) and I read another file and update the old map. the error occurs while the updating step.
Can anybody help me with the info I gave above? Thanks a lot
The code is pretty long.....I just erase the previous key and then insert a new one, it seems not complicated.....but drives me crazy....could you guess what happened here?
Thanks A lot for all your answers! And I found it is really a good place for solving problems. Thanks again, I'll try to simplify my codes and add it here today or tomorrow.
Update: I used the code from MSN and it works, thanks a lot that you solved my problem without seeing my code......also many thanks to other kind-hearted people here! However, i can only choose one as the answer.
|
The type in question is pair<string, vector<float> >. You will be copying that pair on every insert. If either the string or the vector are big then you could be running out of memory.
Edit: to fix running out of memory, you can change how you insert key-value pairs to:
pair<map::iterator, bool> insert_result= map.insert(make_pair(name, vector<float>());
if (insert.second) { insert_result.first->second.swap(vector_read_in); }
That will ensure that you do not copy memory, only move it.
|
485,371
| 485,445
|
How do I alter this tokenization process to work on a text file with multiple lines?
|
I'm working this source code:
#include <string>
#include <vector>
#include <iostream>
#include <istream>
#include <ostream>
#include <iterator>
#include <sstream>
#include <algorithm>
int main()
{
std::string str = "The quick brown fox";
// construct a stream from the string
std::stringstream strstr(str);
// use stream iterators to copy the stream to the vector as whitespace separated strings
std::istream_iterator<std::string> it(strstr);
std::istream_iterator<std::string> end;
std::vector<std::string> results(it, end);
// send the vector to stdout.
std::ostream_iterator<std::string> oit(std::cout);
std::copy(results.begin(), results.end(), oit);
}
To, instead of tokenizing a single line and putting it into the vector results, it tokenizes a group of lines taken from this text file and puts the resulting words into a single vector .
Text File:
Munroe states there is no particular meaning to the name and it is simply a four-letter word without a phonetic pronunciation, something he describes as "a treasured and carefully-guarded point in the space of four-character strings." The subjects of the comics themselves vary. Some are statements on life and love (some love strips are simply art with poetry), and some are mathematical or scientific in-jokes.
So far, I'm only clear that I need to use a
while (getline(streamOfText, readTextLine)){}
to get the loop running.
But I don't think this would work:
while (getline(streamOfText, readTextLine)) {
cout << readTextLine << endl;
// construct a stream from the string
std::stringstream strstr(readTextLine);
// use stream iterators to copy the stream to the vector as whitespace separated strings
std::istream_iterator it(strstr);
std::istream_iterator end;
std::vector results(it, end);
/*HOw CAN I MAKE THIS INSIDE THE LOOP WITHOUT RE-DECLARING AND USING THE CONSTRUCTORS FOR THE ITERATORS AND VECTOR? */
// send the vector to stdout.
std::ostream_iterator<std::string> oit(std::cout);
std::copy(results.begin(), results.end(), oit);
}
|
Yes, then you have one whole line in readTextLine. Is it that what you wanted in that loop? Then instead of constructing the vector from the istream iterators, copy into the vector, and define the vector outside the loop:
std::vector<std::string> results;
while (getline(streamOfText, readTextLine)){
std::istringstream strstr(readTextLine);
std::istream_iterator<std::string> it(strstr), end;
std::copy(it, end, std::back_inserter(results));
}
You actually don't need to read a line into the string first, if all you need is all words from a stream, and no per-line processing. Just read from the other stream directly like you did in your code. It will not only read words from one line, but from the whole stream, until the end-of-file:
std::istream_iterator<std::string> it(streamOfText), end;
std::vector<std::string> results(it, end);
To do all that manually, like you ask for in the comments, do
std::istream_iterator<std::string> it(streamOfText), end;
while(it != end) results.push_back(*it++);
I recommend you to read a good book on this. It will show you much more useful techniques i think. C++ Standard library by Josuttis is a good book.
|
485,448
| 2,962,150
|
Programmatically access CPU fan on a laptop? (Windows)
|
Is there a Windows standard way to do things such as "start fan", "decrease speed" or the like, from C/C++?
I have a suspicion it might be ACPI, but I am a frail mortal and cannot read that kind of documentation.
Edit: e.g. Windows 7 lets you select in your power plan options such as "passive cooling" (only when things get hot?) vs. "active cooling" (keep the CPU proactively cool?). It seems the OS does have a way to control the fan generically.
|
I am at the moment working on a project that, among other things, controls the computer fans. Basically, the fans are controlled by the superIO chip of your computer. We access the chip directly using port-mapped IO, and from there we can get to the logical fan device. Using port-mapped IO requires the code to run in kernel mode, but windows does not supply any drivers for generic port IO (with good reason, since it is a very powerful tool), so we wrote our own driver, and used that.
If you want to go down this route, you basically need knowledge in two areas: driver development and how to access and interpret superIO chip information. When we started the project, we didn't know anything in either of these areas, so it has been learning by browsing, reading and finally doing. To gain the knowledge, we have been especially helped by looking at these links:
The WDK, which is the Windows Driver Kit. You need this to compile any driver you write for windows, With it comes a whole lot of source code for example drivers, including a driver for general port-mapped IO, called portio.
WinIO has source code for a driver in C, a dll in C that programmatically installs and loads that driver, and some C# code for a GUI, that loads the dll and reads/writes to the ports. The driver is very similar to the one in portio.
lm-sensors is a linux project, that, among other things, detects your superIO chip. /prog/detect/sensors-detect is the perl program, that does the detecting, and we have spent some time going through the code to see how to interface with a superIO chip.
When we were going through the lm-sensors code, it was very nice to have tools like RapidDriver and RW-everything, since they allowed us to simulate a run of sensors-detect. The latter is the more powerful, and is very helpful in visualising the IO space, while the former provides easier access to some operations which map better to the ones in sensors-detect (read/write byte to port)
Finally, you need to find the datasheet of your superIO chip. From the examples, that I have seen, the environment controllers of each chip provide similar functionality (r/w fan speed, read temperature, read chip voltage), but vary in what registers you have to write to in order to get to this functionality. This place has had all the datasheets, we have needed so far.
|
485,525
| 11,101,890
|
round() for float in C++
|
I need a simple floating point rounding function, thus:
double round(double);
round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1
I can find ceil() and floor() in the math.h - but not round().
Is it present in the standard C++ library under another name, or is it missing??
|
It's available since C++11 in cmath (according to http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf)
#include <cmath>
#include <iostream>
int main(int argc, char** argv) {
std::cout << "round(0.5):\t" << round(0.5) << std::endl;
std::cout << "round(-0.5):\t" << round(-0.5) << std::endl;
std::cout << "round(1.4):\t" << round(1.4) << std::endl;
std::cout << "round(-1.4):\t" << round(-1.4) << std::endl;
std::cout << "round(1.6):\t" << round(1.6) << std::endl;
std::cout << "round(-1.6):\t" << round(-1.6) << std::endl;
return 0;
}
Output:
round(0.5): 1
round(-0.5): -1
round(1.4): 1
round(-1.4): -1
round(1.6): 2
round(-1.6): -2
|
485,649
| 501,573
|
Confusing gprof output
|
I ran gprof on a C++ program that took 16.637s, according to time(), and I got this for the first line of output:
% cumulative self self total
time seconds seconds calls s/call s/call name
31.07 0.32 0.32 5498021 0.00 0.00 [whatever]
Why does it list 31.07% of time if it only took .32 seconds? Is this a per-call time? (Wouldn't that be self s/call?)
This is my first time using gprof, so please be kind :)
Edit: by scrolling down, it appears that gprof only thinks my program takes 1.03 seconds. Why might it be getting it so wrong?
|
The bottleneck turned out to be in file I/O (see Is std::ifstream significantly slower than FILE?). I switched to reading the entire file in a buffer and it sped up enormously.
The problem here was that gprof doesn't appear to generate accurate profiling when waiting for file I/O (see http://www.regatta.cs.msu.su/doc/usr/share/man/info/ru_RU/a_doc_lib/cmds/aixcmds2/gprof.htm). In fact, seekg and tellg were not even on the profiling list, and they were the bottleneck!
|
485,730
| 485,744
|
Keys / Values Functionality to Iterators in C++
|
I know this questions has come up in various guises before, but this is slightly different.
I have a class which contains a std::map. Although I wish to use the map for other purposes inside the class, externally I want to expose an iterator adapter to just the values inside the map (ie the second item in the std::pair).
For example in python I might do something like this:
def __iter__(self):
return self._dict.itervalues()
How do I go about doing this in c++, hiding the implementation inside the class?
Thanks,
Dan
|
Have a look at Boost's transform_iterator which provides exactly this kind of functionality:
template <typename K, typename V>
struct get_value {
const V& operator ()(std::pair<K, V> const& p) { return p.second; }
};
class your_class {
typedef map<int, float> TMap;
TMap mymap;
public:
typedef get_value<TMap::key_type, TMap::data_type> F;
typedef
boost::transform_iterator<F, TMap::iterator>
value_iterator;
value_iterator begin() { return make_transform_iterator(mymap.begin(), F()); }
value_iterator end() { return make_transform_iterator(mymap.end(), F()); }
// TODO Same for const versions.
// Rest of the interface …
};
Now you can iterate over the values, e.g. like this:
your_class c;
// Fill c with some values …
copy(c.begin(), c.end(), ostream_iterator<float>(cout, " "));
|
486,087
| 486,409
|
How to call an external program with parameters?
|
I would like to call a windows program within my code with parameters determined within the code itself.
I'm not looking to call an outside function or method, but an actual .exe or batch/script file within the WinXP environment.
C or C++ would be the preferred language but if this is more easily done in any other language let me know (ASM, C#, Python, etc).
|
When you call CreateProcess(), System(), etc., make sure you double quote your file name strings (including the command program filename) in case your file name(s) and/or the fully qualified path have spaces otherwise the parts of the file name path will be parsed by the command interpreter as separate arguments.
system("\"d:some path\\program.exe\" \"d:\\other path\\file name.ext\"");
For Windows it is recommended to use CreateProcess(). It has messier setup but you have more control on how the processes is launched (as described by Greg Hewgill). For quick and dirty you can also use WinExec().
(system() is portable to UNIX).
When launching batch files you may need to launch with cmd.exe (or command.com).
WinExec("cmd \"d:some path\\program.bat\" \"d:\\other path\\file name.ext\"",SW_SHOW_MINIMIZED);
(or SW_SHOW_NORMAL if you want the command window displayed ).
Windows should find command.com or cmd.exe in the system PATH so in shouldn't need to be fully qualified, but if you want to be certain you can compose the fully qualified filename using CSIDL_SYSTEM (don't simply use C:\Windows\system32\cmd.exe).
|
486,252
| 486,259
|
Class design suggestions - C++
|
Background
I am working on a phonetic converter program which converts english text into equivalant regional language text. Regional languages will have more characters than english letters and regional language fonts uses almost all positions (1-255) in a font.
My program supports different fonts and I have created a font class which will have methods gives access to the characters. This class will have 255 methods each representing each character. All these are marked as virtual so that a new font can override necessary character methods.
The methods in this font class are trivial. All methods are single line. Example would be
string StandardFont::consonant1(){
return "a";
}
string StandardFont::consonant2(){
return "b";
}
..
Questions
Will 255 virtual functions in a single class make any performance issues? I know about vtable stuff, but I am not sure how much impact it has in this scenario.
Can anyone suggest an alternate design for this class? Main design goal is to allow derived classes to override necessary methods. I have thought about adding the characters into containers like map or vector and providing method to get the character. But since I will have 255 items and this class is used frequently, I think each time I have to loop the container to get the character, which is again an issue.
Any thought?
|
I suggest you use a standard encoding of non-ASCII (regional) characters.
A standard encoding is called "unicode", for example http://www.joelonsoftware.com/articles/Unicode.html
Anyway: to answer your questions ...
Will 255 virtual functions in a single class make any performance issues?
In a word: no, it won't.
But since I will have 255 items and this class is used frequently, I think each time I have to loop the container to get the character, which is again an issue.
With a vector or a fixed-length array whose length is 256, you wouldn't need to loop ... instead you could index directly, for example:
const char* translations[256] = {
"a",
"bee",
"c!",
...etc...
};
const char* translate(char c)
{
//use the character as an index into the array
int index = c;
//use the translation array (using indexing, not looping)
const char* result = translations[index];
return result;
}
|
486,313
| 531,185
|
How to check if a Server and Client are in the same concurrency model?
|
The concurrency model can be either apartment-threaded or multi-threaded
Question:
How to ensure that both the Client and Server are operating from within the same concurrency model?
|
Sometimes you need to know. Two quick examples:
Performance hit of proxy/stub pairs is a problem
You need to pass around "unmarshallable" data or objects
So, the answer -- if you do need to know:
The server and the client must be designed and implemented to support the same or compatible models. Either one of these scenarios will do:
Both should be MTA, or
Both should be STA, or
The server should be "Both" (supports either)
The Server should be "free-threaded" (but that doesn't buy you anything extra compared to Both, in this scenario)
|
486,435
| 486,498
|
Where can I find MSCVR80.DLL v8.0.50727.3053?
|
I've got a bug from one of our customers and believe that the problem lies with MSVCR80.DLL v8.0.50727.3053 - a version which I cannot find for download anywhere, however a google search turns up plenty of other crash reports.
Latest version on my system (and others here) is 8.0.50727.1433 and the Microsoft Visual C++ 2005 SP1 Redistributable Package (x86) is only version 8.0.5027.762 (currently same as the merge module we use)
Is there an "official" link to get this update? Is it bundled with any other Microsoft products?
EDIT: please don't email it to me, I'm looking for the SxS install.
EDIT2: damn, that wasn't the problem after all :(
|
A thread on the MSDN forums pointed out the answer: msvcr80.dll version 8.0.50727.3053 is included in .NET Framework 3.5 SP1
|
486,454
| 486,465
|
Basic C++ question regarding scope of functions
|
I'm just starting to learn C++ so you'll have to bear with my ignorance. Is there a way to to declare functions such that they can be referenced without being written before the function that uses them. I'm working with one cpp file (not my decision) and my functions call themselves so there is not really a proper order to place them in. Any way to #define functions before they're used or something to that effect?
Or maybe a way to tag them with a scope operator that doesn't entail them actually being part of a class?
Thanks in advance
|
You can write function prototypes before you implement them. A function prototype names a function, its return type, and the type of its arguments. The only thing that needs to be above the call to your function is the prototype. Here's an example:
// prototype
int your_function(int an_argument);
// ...
// here you can write functions that call your_function()
// ...
// implementation of your_function()
int your_function(int an_argument) {
return an_argument + 1;
}
|
486,508
| 486,597
|
How does template argument shadowing work in VS2005?
|
In GCC this code won't compile, because T gets shadowed, however in VS2005 it compiles with no warnings, so what are the assumptions VS compiler is making?
template<typename T>
class Foo
{
template<typename T>
void Bar(const T& bar)
{
...
}
};
|
Found the right answer after 3 months of searching :) It's in 14.6.1/4 of the Standard:
A template-parameter shall not be redeclared within its scope (including nested scopes). A template-parameter shall not have the same name as the template name.
Example:
template<class T, int i> class Y {
int T;
// error: template-parameter redeclared
void f() {
char T;
// error: template-parameter redeclared
}
};
template<class X> class X; // error: template-parameter redeclared
If the Microsoft compiler let it compile without errors or even warnings, it is not conforming. I don't know what could drive it to allow it without moaning. You could try to high warning levels.
|
486,555
| 488,832
|
Is there a correct way to avoid warnings when comparing two different enums?
|
When comparing enums that come from different sources such as those of the following code GCC emits warnings. Is there a way to avoid these warnings without c-style casts?
struct Enumerator
{
enum { VALUE = 5 };
};
template<int V>
struct TemplatedEnumerator
{
enum { VALUE = V };
};
if(Enumerator::VALUE == TemplatedEnumerator<5>::VALUE)
{
...
}
And GCC emits the following type of warning:
GCC: warning: comparison between 'enum ...' and 'enum ...'
|
Simple answer in your case: don't use an enum, use an inline-defined static const int:
struct Enumerator
{
static int const VALUE = 5;
};
template<int V>
struct TemplatedEnumerator
{
static int const VALUE = V;
};
In this special case, that's equivalent and all compilers of the last few years should treat it so (I know for a fact that all the major ones do).
See also: static const Member Value vs. Member enum : Which Method is Better & Why?
|
486,562
| 486,767
|
Variable height items in Win32 ListView
|
Is it possible to have variable size (owner draw) items in the Win32 ListView, if yes, how?
|
Check out WM_MEASUREITEM
|
486,797
| 486,820
|
What is an analog for win32 file locking in boost::interprocess?
|
What sync mechanism should I use to give exclusive access to the text file in boost?
The file will likely be accessed by threads from only one process.
|
If you are sure it will only be accessed from one process, a read-write lock with file handles in thread local storage could be a solution. That would simulate the above with only one writer but several readers.
|
487,035
| 487,039
|
How to Convert 64bit Long Data Type to 16bit Data Type
|
I would like to know how to convert 64 bit long Data Type to any of the 16 bit Data Types. This feature is required in the Ethernet Application to include the Time Stamp. Only 2 Bytes ( 16 bits ) are available to include the Time Stamp. But we are getting 64 bit long as the Time Stamp value from Win API. So a conversion from 64 bit data type to to 16 bit data type is essential.
|
Well, you can't fit 64 bits of information into 16 bits of storage without losing some of the information.
So it's up to you how to quantize or truncate the timestamp. E.g. suppose you get the timestamp in nanosecond precision, but you only need to store it at seconds precision. In that case you divide the 64 bit number by 1000000000 and are left with the seconds. Then it might fit into 16 bits or not (16 bits would only store up to 65535 seconds).
If it won't fit, then you'll have the timestamp wrapping around periodically. Which, again, might be a problem in your case or it might be not a problem.
In any case, if you need to interface an existing library that requires timestamps - figure out what it needs in that timestamp (clock ticks? seconds? years?). Then figure out what the Windows times function that you're using returns. Then convert the Windows time unit into the-library-that-you-use time unit.
|
487,048
| 487,058
|
Difference between const declarations in C++
|
What is the difference between
void func(const Class *myClass)
and
void func(Class *const myClass)
See also:
C++ const question
How many and which are the uses of "const" in C++?
and probably others...
|
The difference is that for
void func(const Class *myClass)
You point to a class that you cannot change because it is const.
But you can modify the myClass pointer (let it point to another class; this don't have any side effects to the caller because it's pointer is copied, it only changes your local the pointer copy)
In contrast
void func(Class *const myClass)
Now myClass points to a class that can be modified while you cannot change the parameter.
|
487,108
| 487,520
|
How to suppress specific warnings in g++
|
I want to suppress specific warnings from g++. I'm aware of the -Wno-XXX flag, but I'm looking for something more specific. I want some of the warnings in -Weffc++, but not all of them. Something like what you can do with lint - disable specific messages.
Is there a built in way in gcc to do this? Do I have to write a wrapper script?
|
Unfortunately, this feature isn't provided by g++. In VC++, you could use #pragma warning to disable some specific warnings. In gcc, the closest you can have is diagnostic pragmas, which let you enable/disable certain types of diagnostics for certain files or projects.
Edit: GCC supports pushing/popping warnings since 4.6.4 (see changelog)
|
487,114
| 487,155
|
C/C++ Header file documentation
|
What do you think is best practice when creating public header files in C++?
Should header files contain no, brief or massive documentation? I've seen everything from almost no documentation (relying on some external documentation) to large specifications of invariants, valid parameters, return values etc. I'm not sure exactly what I prefer, large documentation is nice since you've always access to it from your editor, on the other hand a header file with very brief documentation can often show a complete interface on one or two pages of text giving a much better overview of what's possible to do with a class.
Let's say I go with something like brief or massive documentation. I want something similar to javadoc where I document return values, parameters etc. What's the best convention for that in c++? As far as I can remember doxygen does good stuff with java doc-style documentation, but are there any other conventions and tools for this I should be aware of before going for javadoc style documentation?
|
Usually I put documentation for the interface (parameters, return value, what the function does) in the interface file (.h), and the documentation for the implementation (how the function does) in the implementation file (.c, .cpp, .m).
I write an overview of the class just before its declaration, so the reader has immediate basic information.
The tool I use is Doxygen.
|
487,243
| 487,362
|
Implementation in global functions, or in a class wrapped by global functions
|
I have to implement a set of 60 functions, according to the predefined signatures. They must be global functions, and not some class's member functions. When I implement them, I use a set of nicely done classes provided by 3rd party.
My implementation of most functions is quite short, about 5-10 lines, and deals mostly with different accesses to that 3rd party classes. For some more complicated functions I created a couple of new classes that deal with all the complicated stuff, and I use them in the functions too. All the state information is stored in the static members of my and 3rd party's classes, so I don't have to create global variables.
Question: Would it be better if I implement one big class with 60 member functions, and do all the implementation (that is now in the global functions) there? And each of the functions that I have to write will just call to the corresponding member function in the class.
|
All the state information is stored in the static members of my and 3rd party's classes, so I don't have to create global variables.
That is the keypoint. No, they should definitely not be put into classes. Classes are made to be used for creating objects. In your situation, you would use them just as a scope, for the data and functions. But this is what namespaces already solve better:
namespace stuff {
... 60 functions ...
namespace baz {
... if you want, you can have nested namespaces, to ...
... categorize the functions ...
}
namespace data {
... you can put data into an extra namespace if you want ...
}
}
Creating classes that consist purely only of static members is a bad idea.
|
487,283
| 488,076
|
Storing and Retrieving Dynamically Changing Structures
|
I am creating a game using Allegro/C++. The game is almost done and now, I want to create a map editor. The game contains numerous classes and their number will vary depending on the number of objects the map requires. I was thinking of creating a separate structure to hold level data and store it as a map. The problem is that the size varies according to the map and I've got to use pointers to accommodate objects depending on the number.
What is the best way to store such data and retrieve it.
An example of the structure I was thinking of-
struct Level
{
int soldierCount;
Soldier **soldier;
int taskCount;
int *taskPercentage;
int *taskBitmapX;
int *taskBitmapY;
};
|
So, what you want to do is serialization.
I suggest simply using an already existing library for that. Have a look at this thread: How to serialize in c++ ?
|
487,342
| 490,895
|
Error in QSqlTableModel inherited table
|
I have this class that inherits from QSqlTableModel and it brokes after calling the submitAll() slot, after calling insertPoint some times. Here is the code.
Thanks for the help.
Regards.
#ifndef VWLANDMARKTABLEMODEL_H
#define VWLANDMARKTABLEMODEL_H
#include <QSqlTableModel>
class GraphicsPointLandmarkItem;
class VWLandmarkTableModel : public QSqlTableModel
{
Q_OBJECT
public:
enum Column {
IdColumn=0,
IdImageColumn=1,
UsernameColumn=2,
NameColumn=3,
DefinitionColumn=4
};
VWLandmarkTableModel(QObject *parent=0);
int idImage() const { return m_idImage; }
QString username() const { return m_username; }
void setIdImage(int idImage);
void setUsername(const QString &username);
virtual bool select();
bool insertPoint(GraphicsPointLandmarkItem *item);
signals:
protected:
virtual void setFilter(const QString &filter)
{ QSqlTableModel::setFilter(filter); }
virtual bool insertRowIntoTable(const QSqlRecord &values);
protected slots:
void setDefaults(int row, QSqlRecord &r);
private:
QString m_username;
int m_idImage;
};
#endif // VWLANDMARKTABLEMODEL_H
#include "vwlandmarktablemodel.h"
#include <QtGui>
#include <QtSql>
#include <QtCore>
#include "graphicspointlandmarkitem.h"
VWLandmarkTableModel::VWLandmarkTableModel(QObject *parent)
: QSqlTableModel(parent)
{
setTable("vwLandmark");
setEditStrategy(OnManualSubmit);
connect(this, SIGNAL(primeInsert(int,QSqlRecord&)),
SLOT(setDefaults(int,QSqlRecord&)));
}
void VWLandmarkTableModel::setIdImage(int idImage)
{ m_idImage=idImage; }
void VWLandmarkTableModel::setUsername(const QString &username)
{ m_username=username; }
bool VWLandmarkTableModel::select()
{
Q_ASSERT(!username().isEmpty());
QString stmt="IdImage = %1 AND Username = '%2'";
setFilter(stmt.arg(idImage()).arg(username()));
return QSqlTableModel::select();
}
bool VWLandmarkTableModel::insertPoint(GraphicsPointLandmarkItem *item)
{
QString text;
QTextStream out(&text);
int row=rowCount();
bool ok;
ok=insertRow(row); Q_ASSERT(ok);
QModelIndex idx=index(row, DefinitionColumn);
out<<*item;
ok=setData(idx, text);
Q_ASSERT(ok);
idx=index(row, NameColumn);
ok=setData(idx, tr("New point landmark"));
Q_ASSERT(ok);
return ok;
}
bool VWLandmarkTableModel::insertRowIntoTable(const QSqlRecord &values)
{
QString sql="EXEC InsertLandmark :IdImage,:Definition";
QSqlQuery q;
bool ok;
ok=q.prepare(sql); Q_ASSERT(ok);
q.bindValue(":IdImage", values.value("IdImage"));
q.bindValue(":Definition", values.value("Definition"));
q.setForwardOnly(true);
if(!q.exec()) {
setLastError(q.lastError());
return false;
}
qDebug()<<"hola mundo";
return true;
}
void VWLandmarkTableModel::setDefaults(int row, QSqlRecord &r)
{
r.setValue("IdImage", idImage());
r.setValue("Name", "Unnamed landmark");
r.setValue("Username", username());
}
|
The problem was in my custom select. Calling setFilter() causes a infinite calling loop
|
487,416
| 487,567
|
Making a C++ app scriptable
|
I have several functions in my program that look like this:
void foo(int x, int y)
Now I want my program to take a string that looks like:
foo(3, 5)
And execute the corresponding function. What's the most straightforward way to implement this?
When I say straightforward, I mean reasonably extensible and elegant, but it shouldn't take too long to code up.
Edit:
While using a real scripting language would of course solve my problem, I'd still like to know if there is a quick way to implement this in pure C++.
|
I'd also go for the scripting language answer.
Using pure C++, I would probably use a parser generator, which will will get the token and grammar rules, and will give me C code that exactly can parse the given function call language, and provides me with an syntax tree of that call. flex can be used to tokenize an input, and bison can be used to parse the tokens and transform them into an syntax tree. Alternatively to that approach, Boost Spirit can be used to parse the function call language too. I have never used any of these tools, but have worked on programs that use them, thus I somewhat know what I would use in case I had to solve that problem.
For very simple cases, you could change your syntax to this:
func_name arg1, arg2
Then you can use:
std::istringstream str(line);
std::string fun_name; str >> fun_name;
map[fun_name](tokenize_args(str));
The map would be a
std::map<std::string, boost::function<void(std::vector<std::string>)> > map;
Which would be populated with the functions at the start of your program. tokenize_args would just separate the arguments, and return a vector of them as strings. Of course, this is very primitive, but i think it's reasonable if all you want is some way to call a function (of course, if you want really script support, this approach won't suffice).
|
487,566
| 487,599
|
Why Does This Pointer-Pointer Initialization Seg Fault?
|
I create a pointer-to-pointer of a class object and when I try to create a new object using the pointers it seg-faults. Why does this happen?
struct Level
{
int SoldierCount;
Soldier **soldier;
int taskCount;
int *taskPercentage;
int *taskBitmapX;
int *taskBitmapY;
}level;
void createMap()
{
//Input and Declartion of various variabls goes here
level.soldier = new Soldier* [level.SoldierCount];
//Seg Faults Here
level.Soldier[i] = new Soldier(initX, initY, initDirection, steps);
}
The Soldier Class Constructor:
Soldier(int, int, int, int);
|
With empty Soldier constructor your code works fine (except for corrected typos, like lowercase level.soldier[])
Please post the constructor body.
|
487,866
| 492,525
|
HOT(Heap On Top) Queues
|
Could anyone point me to an example implementation of a HOT Queue or give some pointers on how to approach implementing one?
|
Here is a page I found that provides at least a clue toward what data structures you might use to implement this. Scroll down to the section called "Making A* Scalable." It's unfortunate that the academic papers on the subject mention having written C++ code but don't provide any.
|
488,456
| 488,474
|
Why can't I get a decent function browser in Visual Studio 2008?
|
There is no way to list the functions in a C++ solution for me... I have a class browser but that isn't helpful since this project has no classes. I need a simple list of all the functions in a c++ file and then just double click one to jump to its source (as a side pane, NOT as a dropdown)... I have to be missing something here as I have looked and googled for something so simple.
|
I've never found a built-in way to do this, in 10 years of working with Visual Studio. However, Visual Assist X will do this for you in its Outline View. The down side is that it's not free, but I've found it to be an essential tool for working with C++ in Visual Studio. Well worth the money IMHO.
|
488,687
| 488,697
|
Refactoring a class in C++
|
I have a class A which implements many functions. Class A is very stable.
Now I have a new feature requirement, some of whose functionality matches that implemented by A. I cannot directly inherit my new class from class A, as that would bring lot of redundancy into my new class.
So, should i duplicate the common code in both the classes?
Or, should i create a new base class and move the common code to base class, and derive class A and the new class from it? But this will lead to changes in my existing class.
So, which would be a better approach?
|
Unless there is a very good reason not to modify class A, refactor and make a common base (or even better, a common class that both can use, but not necessarily derive from).
You can always use private inheritance to gain access to the shared functionality without modifying class As external interface - this change would require a rebuild, but nothing more. Leave all the functions on class A, and just have them forward to the shared implementation class.
One reason you might not want to refactor, but rather copy the code is if it's likely that the new class' functionality will change, but without the same change being needed in the old class. One of the reasons for not duplicating code is so that a fix or a change needs only to be made in one place. If changes are going to happen that will break the original class, then maybe you want to copy the code instead. Although in most cases, this will only happen if the two classes aren't as similar as you thought, and you'd be fighting to try and abstract a common set of functionality.
|
488,729
| 488,762
|
Are these appropriate practices when working with std::map?
|
I have some questions on using std::map:
Is using an enum as the key in std::map a good practice? Consider the following code:
enum Shape{
Circle,
Rectangle
};
int main(int argc, char* argv[])
{
std::map<Shape,std::string> strMap;
// strMap.insert(Shape::Circle,"Circle"); // This will not compile
strMap[Shape::Circle] = "Circle"; // But this will work
return 0;
}
In the above example, why is the call to insert() generating a compiler error while the overloaded [] operator works correctly? Which of these methods is recommended for inserting items into a std::map?
I understand that when the find() method is used on the std::map class, it is not doing a sequential search in the container but doing some logarithmic search which will be much faster than sequential search. Is this understanding correct?
|
Having an enum as key_type is not bad by itself. (edit) But if you only use sequential enum-values, a std::vector with O(1) access is even better.
insert must be used like this: mapVar.insert(make_pair(key, value));
See also cppreference.com.
Yes, std::map has O(log(n)) lookup, as guaranteed by the standard, and this is faster than O(n) if n is sufficiently high.
|
488,837
| 488,880
|
How do I create a GUI for a windows application using C++?
|
I am deciding on how to develop a GUI for a small c++/win32 api project (working Visual Studio C++ 2008). The project will only need a few components to start off the main process so it will be very light weight (just 1 button and a text box pretty much...). My question is this:
I don't have experience developing GUIs on windows but I can learn easily. So, what should I use? A Visual editor (drag and drop code generationg: my preference for desktop GUI designing by far (java/swing)). Or should I use a speicific library? Either way, WHICH library or visual editor should I use? I heard someone mention writing the GUI in C#, then calling the C++ code... the thing is, that this is such a simple GUI I would find it easier to just keep it all in C++, but I'm open to whatever the best suggestion is.
|
If you're doing a very simple GUI and you're already using Visual Studio then it may make sense to just go with MFC. You can just use the Visual Studio MFC wizard to create a dialog based application, drop two controls on it and away you go.
MFC is dated and has its fair share of annoyances, but it will certainly do the job for you if you're just talking about a button and a text box.
I don't have any experience with Qt, so I can't compare the two.
|
488,874
| 488,977
|
How to reset a class using placment delete/new from a template?
|
I have a pool manager template class. When a class object gets added back to the pool manager I would like to reset it back to it's initial state. I would like to call the placment destructor and placment constructor on it so it gets fully reset for the next time it is given out by the pool manager. I've tried many ways to get this to work but I'm stumped. Here is an example of what I have tried.
template <class T>
void PoolClass<T>::ReleaseToPool(T *obj)
{
obj->~T(); //call destructor
obj->T::T(); //call constructor
//also tried new (obj)T(); //but this doesn't seem to work either
//then misc code to add a pointer to the object
//to my list of available objects for re-use later
}
I've tried a bunch of different syntaxes and none seem to work. The code itself is cross platform so should compile using gcc ( under mingw or linux or mac ) and for windows I'm still using vs 2003.
|
How about:
template <class T>
void PoolClass<T>::ReleaseToPool(T *obj)
{
obj->~T(); //call destructor
obj = new ((void *)obj)T(); //call constructor
// add a pointer to the object to the list...
}
|
488,959
| 488,989
|
How do you create a static template member function that performs actions on a template class?
|
I'm trying to create a generic function that removes duplicates from an std::vector. Since I don't want to create a function for each vector type, I want to make this a template function that can accept vectors of any type. Here is what I have:
//foo.h
Class Foo {
template<typename T>
static void RemoveVectorDuplicates(std::vector<T>& vectorToUpdate);
};
//foo.cpp
template<typename T>
void Foo::RemoveVectorDuplicates(std::vector<T>& vectorToUpdate) {
for(typename T::iterator sourceIter = vectorToUpdate.begin(); (sourceIter != vectorToUpdate.end() - 1); sourceIter++) {
for(typename T::iterator compareIter = (vectorToUpdate.begin() + 1); compareIter != vectorToUpdate.end(); compareIter++) {
if(sourceIter == compareIter) {
vectorToUpdate.erase(compareIter);
}
}
}
}
//SomeOtherClass.cpp
#include "foo.h"
...
void SomeOtherClass::SomeFunction(void) {
std::vector<int> myVector;
//fill vector with values
Foo::RemoveVectorDuplicates(myVector);
}
I keep getting a linker error, but it compiles fine. Any ideas as to what I'm doing wrong?
UPDATE: Based on the answer given by Iraimbilanja, I went and rewrote the code. However, just in case someone wanted working code to do the RemoveDuplicates function, here it is:
//foo.h
Class Foo {
template<typename T>
static void RemoveVectorDuplicates(T& vectorToUpdate){
for(typename T::iterator sourceIter = vectorToUpdate.begin(); sourceIter != vectorToUpdate.end(); sourceIter++) {
for(typename T::iterator compareIter = (sourceIter + 1); compareIter != vectorToUpdate.end(); compareIter++) {
if(*sourceIter == *compareIter) {
compareIter = vectorToUpdate.erase(compareIter);
}
}
}
};
Turns out that if I specify std::vector in the signature, the iterators don't work correctly. So I had to go with a more generic approach. Also, when erasing compareIter, the next iteration of the loop produces a pointer exception. The post decrement of compareIter on an erase takes care of that problem. I also fixed the bugs in the iterator compare and in the initialization of compareIter in the 2nd loop.
UPDATE 2:
I saw that this question got another up vote, so figured I'd update it with a better algorithm that uses some C++14 goodness. My previous one only worked if the type stored in the vector implemented operator== and it required a bunch of copies and unnecessary comparisons. And, in hindsight, there is no need to make it a member of a class. This new algorithm allows for a custom compare predicate, shrinks the compare space as duplicates are found and makes a significantly smaller number of copies. The name has been changed to erase_duplicates to better conform to STL algorithm naming conventions.
template<typename T>
static void erase_duplicates(T& containerToUpdate)
{
erase_duplicates(containerToUpdate, nullptr);
}
template<typename T>
static void erase_duplicates(T& containerToUpdate,
std::function<bool (typename T::value_type const&, typename T::value_type const&)> pred)
{
auto lastNonDuplicateIter = begin(containerToUpdate);
auto firstDuplicateIter = end(containerToUpdate);
while (lastNonDuplicateIter != firstDuplicateIter) {
firstDuplicateIter = std::remove_if(lastNonDuplicateIter + 1, firstDuplicateIter,
[&lastNonDuplicateIter, &pred](auto const& compareItem){
if (pred != nullptr) {
return pred(*lastNonDuplicateIter, compareItem);
}
else {
return *lastNonDuplicateIter == compareItem;
}
});
++lastNonDuplicateIter;
}
containerToUpdate.erase(firstDuplicateIter, end(containerToUpdate));
}
|
Short Answer
Define the function in the header, preferably inside the class definition.
Long answer
Defining the template function inside the .cpp means it won't get #included into any translation units: it will only be available to the translation unit it's defined in.
Hence RemoveVectorDuplicates must be defined in the header, as this is the only way the compiler can text-substitute the template arguments, hence instantiating the template, producing an usable class.
There are two workarounds for this inconvenience
First, you can remove the #include "foo.h" from the .cpp and add another one, in the end of the header:
#include "foo.cpp"
This lets you organize your files consistently, but doesn't provide the usual advantages of separate compilation (smaller dependencies, faster and rarer compiles).
Second, you can just define the template function in the .cpp and explicitly instantiate it for all the types it'll be ever used with.
For example, this can go in the end of the .cpp to make the function usable with ints:
template void Foo::RemoveVectorDuplicates(std::vector<int>*);
However, this assumes you only use templates to save some typing, rather than to provide true genericity.
|
489,364
| 491,069
|
transform_iterator compile problem
|
HI,
I don't like posting compile problems, but I really can't figure this one out. Using this code:
#include <map>
#include <boost/iterator/transform_iterator.hpp>
using namespace std;
template <typename K, typename V>
struct get_value
{
const V& operator ()(std::pair<K, V> const& p) { return p.second; }
};
class test
{
typedef map<int, float> TMap;
TMap mymap;
public:
typedef get_value<TMap::key_type, TMap::value_type> F;
typedef boost::transform_iterator<F, TMap::iterator> transform_iterator;
transform_iterator begin()
{
return make_transform_iterator(mymap.begin(), F());
}
};
Getting this compile error:
transform_iterator.hpp(43) : error C2039: 'result_type' : is not a member of 'get_value<K,V>'
with
[
K=int,
V=std::pair<const int,float>
]
Can anyone explain why this isn't working? I'm using Visual Studio 7.0 with boost 1.36.0
Thanks.
|
Since you also asked for an explanation
The transform_iterator needs to know the return type of the function called in order to instantiate itself. This is determined via result_of (found in <boost/utility/result_of.hpp>
If you use a function object, you need to define a member result_type to specify the result type of the object. (since an object doesn't have a 'return type' as such)
If you would have used a regular function, result_of would be able to figure it out on his own, e.g.:
template <typename K, typename V>
const V & get_value(std::pair<K, V> const & p) { return p.second; }
class test
{
typedef map<int, float> TMap;
TMap mymap;
public:
typedef boost::function< const TMap::mapped_type & (const TMap::value_type &) > F;
typedef boost::transform_iterator<F, TMap::iterator> transform_iterator;
transform_iterator begin()
{
return boost::make_transform_iterator(mymap.begin(), &get_value< int, float >);
}
};
|
489,880
| 489,900
|
Code Dependency documentation software
|
I am looking for a tool to document legacy source code for an embedded C project I work with. I had it in my mind that there was a tool that would create charts of the various C and .h files, but I can't recall what it is called. Does anyone know of such a tool?
|
There's a big list at this url too.
|
490,005
| 490,099
|
Best c++ container to strip items away from?
|
I have a list of files (stored as c style strings) that I will be performing a search on and I will remove those files that do not match my parameters. What is the best container to use for this purpose? I'm thinking Set as of now. Note the list of files will never be larger than when it is initialized. I'll only be deleting from the container.
|
I would definitely not use a set - you don't need to sort it so no point in using a set. Set is implemented as a self-balancing tree usually, and the self-balancing algorithm is unnecessary in your case.
If you're going to be doing this operation once, I would use a std::vector with remove_if (from <algorithm>), followed by an erase. If you haven't used remove_if before, what it does is go through and shifts all the relevant items down, overwriting the irrelevant ones in the process. You have to follow it with an erase to reduce the size of the vector. Like so:
std::vector<const char*> files;
files.erase(remove_if(files.begin(), files.end(), RemovePredicate()), files.end());
Writing the code to do the same thing with a std::list would be a little bit more difficult if you wanted to take advantage of its O(1) deletion time property. Seeing as you're just doing this one-off operation which will probably take so little time you won't even notice it, I'd recommend doing this as it's the easiest way.
And to be honest, I don't think you'll see that much difference in terms of speed between the std::list and std::vector approaches. The vector approach only copies each value once so it's actually quite fast, yet takes much less space. In my opinion, going up to a std::list and using three times the space is only really justified if you're doing a lot of addition and deletion throughout the entire application's lifetime.
|
490,235
| 490,351
|
hostname not translated into an IP address using Winsock
|
getaddrinfo() does not translate a hostname into an IP address and consequently does not connect() to the server. Is something wrong with my implementation - compiles with no warning messages?
Is this function call to connect correct?
connect(client, result->ai_addr, result->ai_addrlen)
Full implementation listed below:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
int main (
int argc,
char* argv[])
{
if (argc != 3)
{
cerr << "Usage: " << argv[0] << " [hostname] [port number]\n";
exit(EXIT_FAILURE);
}
WSADATA wsaData;
WORD wVersionRequested;
int wError;
wVersionRequested = MAKEWORD(2, 2);
wError = WSAStartup(wVersionRequested, &wsaData);
if (wError != 0)
{
cerr << "WSAStartup failed with error: " << wError << endl;
exit (EXIT_FAILURE);
}
/*
* Confirm that the WinSock DLL supports 2.2.
* Note that if the DLL supports versions greater
* than 2.2 in addition to 2.2, it will still return
* 2.2 in wVersion since that is the version we
* requested.
*/
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
cerr << "Could not find a usable version of Winsock.dll." << endl;
WSACleanup();
exit(EXIT_FAILURE);
} else {
cout << "The Winsock 2.2 dll was found." << endl;
}
SOCKET client;
if ((client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == SOCKET_ERROR)
{
cerr << "Error: socket() return value == SOCKET_ERROR" << endl;
WSACleanup();
exit (EXIT_FAILURE);
}
cout << "Created a socket." << endl;
struct addrinfo *result = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if ((wError = getaddrinfo(
argv[1],
argv[2],
&hints,
&result)) !=0 )
{
freeaddrinfo(result);
WSACleanup();
if (wError == 11001)
{
cerr << "Error: occurred: getaddrinfo() failed "
<< wError << " - Host not found." << endl;
exit(EXIT_FAILURE);
}
cerr << "Error: occurred: getaddrinfo() failed "
<< wError << endl;
exit(EXIT_FAILURE);
}
/*
* Attempt to connect to the Server
*
*/
switch (wError = connect(client, result->ai_addr, result->ai_addrlen)) {
case 0:
cerr << "Resolved hostname." << endl;
break;
case SOCKET_ERROR:
wError = WSAGetLastError();
cerr << "Error: connet() failed "
"Details: " << wError << endl;
closesocket(client);
freeaddrinfo(result);
WSACleanup();
exit(EXIT_FAILURE);
break;
default:
cerr << "Fatal connect() error: unexpected "
"return value." << endl;
closesocket(client);
freeaddrinfo(result);
WSACleanup();
exit(EXIT_FAILURE);
break;
}
cout << "Connected to server." << endl;
closesocket(client);
freeaddrinfo(result);
WSACleanup();
exit(EXIT_SUCCESS);
}
|
getaddrinfo may be giving you an IPv6 address, or perhaps the machine has more than one IP address and you're trying to connect to the wrong one.
Also, if your server is listening on 127.0.0.1 and you try to connect to the real IP address, the connection will fail. Similarly, if the server is listening on the real IP address and you try to connect using 127.0.0.1, the connection will fail. If the server listens on 0.0.0.0, both addresses should work.
To listen on 0.0.0.0, you would have code similar to this:
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port=htons( port_num );
bind( s, (sockaddr *)&sin, sizeof( sin ) );
|
490,403
| 490,409
|
There are Strings in C++?
|
I have been learning C++ with some books from school that are from the 80's and I'm not really sure if they are strings in C++ or just really long arrays of type char. Can anyone help?
|
There is a string class in C++.
|
490,430
| 490,518
|
LoaderLock error on program termination
|
I have recently integrated the .NET NLog logging component into one of our applications which developed purely in unmanaged code (C++ and VB6 components compiled in Visual Studio 6). We have a bunch of C++ application talking to NLog via a COM interface.
Everything is working fine at the moment but I do notice that the following message pops up (in the output window if debugging the C++ component in VS6; as a prompt in the IDE if debugging NLog via VS 2005) during program termination:
LoaderLock was detected Message:
Attempting managed execution inside OS
Loader lock. Do not attempt to run
managed code inside a DllMain or image
initialization function since doing so
can cause the application to hang.
The DllMain is as follows:
extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
_Module.Init(ObjectMap, hInstance);
DisableThreadLibraryCalls(hInstance);
}
else if (dwReason == DLL_PROCESS_DETACH)
_Module.Term();
return TRUE; // ok
}
My guess is that _Module.Term(); now includes the releasing of some .NET references (I am keeping a reference to a NLog object in one of my C++ classes to avoid having to instantiate and release each time) which is causing this warning to pop up.
My question: is this safe to ignore? If it isn't, what is a good workaround? (the best I can think of is to instantiate a reference to that NLog object and release it every time I want to write to the log file...not the most elegant of solutions)
|
It is most definitely not safe to ignore this message. If you hit this message, you've almost certainly created a real loader lock policy violation. This is a very serious error and can cause unpredictable behavior in a program (including deadlock).
The best way to avoid this is to not access any other .Net Objects/Functions directly or indirectly inside of DLL main. For your case, it's probably best to use a different cache policy. Perhaps create a ref counted object to hold the .Net reference. That way the object will be released before DllMain is called for unload (the dll can't be unloaded until all of your objects are destroyed).
|
490,487
| 490,496
|
Returning a reference from a constant function
|
#include "iostream"
#include "vector"
class ABC {
};
class VecTest {
std::vector<ABC> vec;
public:
std::vector<ABC> & getVec() const { //Here it errors out
return vec;
}
};
Removing the const fixes it , is it not the case that getVec is a constant method. So why is this not allowed?
|
What you should probably be doing is returning a const reference.
const std::vector& getVec() const { return vec; }
It's not allowed because you've said getVec is a const method, meaning the method should not change the this object in any way. Returning a non-const reference would possibly allow its object to be changed, so the compiler doesn't allow it.
|
490,720
| 490,809
|
Including boost::filesystem produces linking errors
|
Ok first off, I am linking to boost_system and boost_filesystem.
My compiler is a custom build of MinGW with GCC 4.3.2
So when I include:
#include "boost/filesystem.hpp"
I get linking errors such as:
..\..\libraries\boost\libs\libboost_system.a(error_code.o):error_code.cpp:
(.text+0xe35)||undefined reference to `_Unwind_Resume'|
..\..\libraries\boost\libs\libboost_system.a(error_code.o):error_code.cpp:
(.eh_frame+0x12)||undefined reference to `__gxx_personality_v0'|
Which after a little searching I found is most commonly when you try to link a C++ program with gcc, the GNU C compiler. But I printed out the exact build command that Code::Blocks is running, and it is definitely linking with g++.
If I comment out this include, everything works fine.
Any ideas? Also, as a side, anyone know of a good place to get windows binaries for boost? The build system is giving me issues, so I'm using some binaries that came with this custom MinGW package
|
Ok, I found the problem. It's a bit convoluted.
GCC is gradually becoming more IS 14882 compliant in the 4.x branch. As they go on, they are removing deprecated non-standards complaint features.
While 4.1.x seem to only have them deprecated and not removed, 4.3.x seems to actually have them removed. What this means is 4.3.x and greater have some backwards compatibility issues with things compiled in the 3.x branch (which used the deprecated and now removed features)
I was using a mix and match combination of binaries that had been compiled with GCC 3.x, 4.1.x and 4.3.x so no matter which one I used, I got a similar error, because at least one binary I was linking to was incompatible with the compiler I was trying at the moment.
I'm now using GCC 4.1.2 and most of my binaries have been compiled with it. I am still how ever using a few binaries from 3.x, which is why I am not upgrading to 4.3.x just yet.
Hope that was less confusing to read than it was to write...
This seems to be a good post addressing some of the issues as they were with 4.1.x
|
490,737
| 491,006
|
Making GCC and other C++ compilers very strict
|
I'm working on a large collaborative C++ project that is both developed and run on various flavors of Linux, OS X and Windows. We compile across these platforms with GCC, Visual Studio C++ and the Intel C++ compiler. As more and more people start developing code for the project, we're starting to see weird errors in compilation and runtime that are specific to particular compilers on particular operating systems. An example of this is implicit inclusion of headers that certain OS/compiler pairs seem to find for you, accidentally overloading a function from a base class in a derived class.
My goal is to make compilation on GCC more strict and catch more errors across all platforms so that we don't keep running into these problems. Here's my list of flags that I'm thinking about trying out for GCC that I've found via Google and the GCC man pages:
-Wall
-Wextra
-Winit-self
-Wold-style-cast
-Woverloaded-virtual
-Wuninitialized
-Wmissing-declarations
-Winit-self
-ansi
-pedantic
What are the other flags that people use to make GCC (and less importantly Visual Studio C++ and the Intel C++ Compiler) obey a stricter standard of the C++ language? Be specific about which compiler and version you're talking about, as some of these might not be implemented in all versions of all compilers.
|
Beside the pedantic-error that everyone else suggested, IMO, it's always good to run lint as part of your compile process.
There are some tools out there:
cpplint (free)
gimple lint
coverity
They will save a lot of your time.
|
490,773
| 491,120
|
How is the C++ exception handling runtime implemented?
|
I am intrigued by how the C++ exception handling mechanism works. Specifically, where is the exception object stored and how does it propagate through several scopes until it is caught? Is it stored in some global area?
Since this could be compiler specific could somebody explain this in the context of the g++ compiler suite?
|
Implementations may differ, but there are some basic ideas that follow from requirements.
The exception object itself is an object created in one function, destroyed in a caller thereof. Hence, it's typically not feasible to create the object on the stack. On the other hand, many exception objects are not very big. Ergo, one can create e.g a 32 byte buffer and overflow to heap if a bigger exception object is actually needed.
As for the actual transfer of control, two strategies exist. One is to record enough information in the stack itself to unwind the stack. This is basically a list of destructors to run and exception handlers that might catch the exception. When an exception happens, run back the stack executing those destructors until you find a matching catch.
The second strategy moves this information into tables outside the stack. Now, when an exception occurs, the call stack is used to find out which scopes are entered but not exited. Those are then looked up in the static tables to determine where the thrown exception will be handled, and which destructors run in between. This means there is less exception overhead on the stack; return addresses are needed anyway. The tables are extra data, but the compiler can put them in a demand-loaded segment of the program.
|
490,803
| 490,817
|
Describing header file locations in makefile
|
In a new project I am working on I have the following dir structure:
Project_base
|---- src
|---- bin
|---- h
| Makefile
And in my source files I have includes that look like so:
#include "../h/SomeHeaderFile.h"
instead of the more correct form:
#include "SomeHeaderFile.h"
What do I need to add to my makefile so that I can removed the relative path includes so they will look normal?
ADDITION: also, where do I set this in CDT (C++ for eclipse) so that in design time this is reflected as well?
|
You need to add -I../h in the list of parameters you pass to gcc.
|
491,000
| 491,511
|
friend class : inherited classes are not friend as well?
|
In C++, I have a class A which is friend with a class B.
I looks like inherited classes of B are not friend of class A.
I this a limitation of C++ or my mistake ?
Here is an example. When compiling, I get an error on line "return new Memento":
Memento::Memento : impossible to access private member declared in Memento.
class Originator;
class Memento
{
friend class Originator;
Memento() {};
int m_Data;
public:
~Memento() {};
};
class Originator
{
public:
virtual Memento* createMemento() = 0;
};
class FooOriginator : public Originator
{
public:
Memento* createMemento()
{
return new Memento; // Impossible to access private member of Memento
}
};
void main()
{
FooOriginator MyOriginator;
MyOriginator.createMemento();
}
I could of course add FooOriginator as friend of Memento, but then, this means I would have to add all Originator-inherited classes as friend of Memento, which is something I'd like to avoid.
Any idea ?
|
See: Friend scope in C++
Voted exact duplicate.
I looks like inherited classes of B are not friend of class A.
Correct
I this a limitation of C++ or my mistake ?
It is the way C++ works. I don't see it as a limitation.
|
491,060
| 491,095
|
How to convert standard IP address format string to hex and long?
|
Does anyone know how to get the IP address in decimal or hex from standard IP address format string ("xxx.xxx.xxx.xxx")?
I've tried to use the inet_addr() function but didn't get the right result.
I tested it on "84.52.184.224"
the function returned 3770168404 which is not correct (the correct result is 1412741344).
Thanks!
|
The htonl, htons, ntohl, ntohs functions can be used to convert between network and local byte orders.
|
491,199
| 491,341
|
Why don't Java, C# and C++ have ranges?
|
Ada, Pascal and many other languages support ranges, a way to subtype integers.
A range is a signed integer value which ranges from a value (first) to another (last).
It's easy to implement a class that does the same in OOP but I think that supporting the feature natively could let the compiler to do additional static checks.
I know that it's impossible to verify statically that a variabile defined in a range is not going to "overflow" runtime, i.e. due to bad input, but I think that something could be done.
I think about the Design by Contract approach (Eiffel) and the Spec# ( C# Contracts ), that give a more general solution.
Is there a simpler solution that checks, at least, static out-of-bound assignment at compile time in C++, C# and Java? Some kind of static-assert?
edit: I understand that "ranges" can be used for different purpose:
iterators
enumerators
integer subtype
I would focus on the latter, because the formers are easily mappable on C* language .
I think about a closed set of values, something like the music volume, i.e. a range that goes from 1 up to 100. I would like to increment or decrement it by a value. I would like to have a compile error in case of static overflow, something like:
volume=rangeInt(0,100);
volume=101; // compile error!
volume=getIntFromInput(); // possible runtime exception
Thanks.
|
Subrange types are not actually very useful in practice. We do not often allocate fixed length arrays, and there is also no reason for fixed sized integers. Usually where we do see fixed sized arrays they are acting as an enumeration, and we have a better (although "heavier") solution to that.
Subrange types also complicate the type system. It would be much more useful to bring in constraints between variables than to fixed constants.
(Obligatory mention that integers should be arbitrary size in any sensible language.)
|
491,304
| 494,714
|
Pimpl idiom with inheritance
|
I want to use pimpl idiom with inheritance.
Here is the base public class and its implementation class:
class A
{
public:
A(){pAImpl = new AImpl;};
void foo(){pAImpl->foo();};
private:
AImpl* pAImpl;
};
class AImpl
{
public:
void foo(){/*do something*/};
};
And I want to be able to create the derived public class with its implementation class:
class B : public A
{
public:
void bar(){pAImpl->bar();}; // Can't do! pAimpl is A's private.
};
class BImpl : public AImpl
{
public:
void bar(){/*do something else*/};
};
But I can't use pAimpl in B because it is A's private.
So I see some ways to solve it:
Create BImpl* pBImpl member in B, and pass it to A with additional A constructor, A(AImpl*).
Change pAImpl to be protected (or add a Get function), and use it in B.
B shouldn't inherit from A. Create BImpl* pBImpl member in B, and create foo() and bar() in B, that will use pBImpl.
Any other way?
What should I choose?
|
class A
{
public:
A(bool DoNew = true){
if(DoNew)
pAImpl = new AImpl;
};
void foo(){pAImpl->foo();};
protected:
void SetpAImpl(AImpl* pImpl) {pAImpl = pImpl;};
private:
AImpl* pAImpl;
};
class AImpl
{
public:
void foo(){/*do something*/};
};
class B : public A
{
public:
B() : A(false){
pBImpl = new BImpl;
SetpAImpl(pBImpl);
};
void bar(){pBImpl->bar();};
private:
BImpl* pBImpl;
};
class BImpl : public AImpl
{
public:
void bar(){/*do something else*/};
};
|
491,487
| 2,187,462
|
DirectX Font tutorial that doesn't use GDI
|
Does anyone have any tutorials/info for creating and rendering fonts in native directx 9 that doesn't use GDI? (eg doesn't use ID3DXFont).
I'm reading that this isn't the best solution (due to accessing GDI) but what is the 'right' way to render fonts in dx?
|
ID3DXFont is a great thing for easy to use, early, debug output. However, it does use the GDI for font rasterization (not hardware accelerated) and there is a significant performance hit (try it, its actually very noticable). As of DirectX 11, though, fonts will be rendered with Direct2D and be hardware accelerated.
The fastest way to render text is using what's called "Bitmap Fonts". I would explain how to do this, except that there is a lot of different ways to do implement this technique, each differing in complexity and capability. It can be as simple as a system that loads a pre-created texture and draws the letters from that, or a system that silently registers a font with Windows and creates a texture in memory at load-time (The engine I developed with a friend did this, it was very slick). Either way, you should see a very noticable performance increase with bitmap fonts.
|
491,883
| 495,326
|
Howto format a boost::date_time-object as per RFC 3339
|
I want to use the date_time library in boost to represent time in my application. This application will generate Atom feeds, which in turn mandates time-stamps in the format specified in RFC 3339, for example "1990-12-31T23:59:60Z" or "1990-12-31T15:59:60-08:00".
So, how do I format time according to this RFC?
I have been reading the Date Time Input/Output documentation all day, and I can't seem to find out how to put the Z at the end when I need it. Also, the RFC supports an optional fractional second, but only one digit of it (eg. "1990-12-31T23:59:60.5Z") (*). I can't seem to find out how to do this either.
I could always write my own formatting routine that reads out the different needed fields, but that seems to me to be working against the grain of the date_time library.
Any experience with writing formatters for this library? Or am I doing the wrong thing?
(*): It seems to me that the ABNF given in the RFC only allows one-digit fractional seconds, but the examples in the same RFC have two-digit fractional seconds. What is that supposed to mean?
|
ABNF from RFC says that there must be at least one digit after dot, there is no defined maximum.
There is no real need for the Z, you can use 00:00 instead, and this is possible with facets
In some rare circumstances date_time will generate a "Z". See code snapshot from boost (local_date_time.hpp) that suggests this is below:
std::string zone_name(bool as_offset=false) const
{
if(zone_ == boost::shared_ptr()) {
if(as_offset) {
return std::string("Z");
}
else {
return std::string("Coordinated Universal Time");
}
...
There is similar if in zone_abbrev function...
And example usage of this
slimak@daradei:~/store/kodowanie/moje/test$ cat boost_date_time.cpp
#include "boost/date_time.hpp"
#include "boost/date_time/local_time/local_time.hpp"
using namespace boost::posix_time;
using namespace boost::local_time;
int main()
{
local_date_time t = local_sec_clock::local_time(time_zone_ptr());
local_time_facet* lf(new local_time_facet("%Y-%m-%dT%H:%M:%S%F%Q"));
std::cout.imbue(std::locale(std::cout.getloc(), lf));
std::cout << t << std::endl;
return 0;
}
slimak@daradei:~/store/kodowanie/moje/test$ g++ boost_date_time.cpp && ./a.out
2009-01-30T12:15:56Z
slimak@daradei:~/store/kodowanie/moje/test$
|
491,972
| 492,007
|
Giving to child access to parent's member by reference - is it OK?
|
C++ newbie question. Please, verify I'm doing it right.
I have a global application class spawning it's little kids and I need to give the kids access to some of the application facilities. So I decided to pass them to children by reference.
I tested the idea as show below. It seems to work fine. I just wanted to make sure I'm not doing something dangerous. Might be there any pitfalls I overlooked?
Dad creates children and gives them his car keys:
#include <iostream>
using namespace std;
class CCarKeys
{
public:
CCarKeys(const string& Name) : _Name(Name) {}
string _Name;
};
class CChild
{
public:
CChild(CCarKeys& CarKeys) : _Name("Child"), _CarKeys(CarKeys) {}
string _Name;
CCarKeys& _CarKeys;
void TestHasKeys() {cout << "I got " << _CarKeys._Name << endl;}
};
class CDad
{
public:
CDad() : _Name("Dad"), _HondaCarKeys("Honda keys"), _ChevyCarKeys("Chevy keys") {}
string _Name;
CCarKeys _HondaCarKeys;
CCarKeys _ChevyCarKeys;
CChild *_Boy;
CChild *_Girl;
void MakeBoy() {_Boy= new CChild(_HondaCarKeys);}
void MakeGirl() {_Girl= new CChild(_ChevyCarKeys);}
};
int main ()
{
CDad Dad;
Dad.MakeBoy();
Dad.MakeGirl();
Dad._Boy->TestHasKeys();
Dad._Girl->TestHasKeys();
}
|
Looks good to me (if keys is all they need). They might need some other services from Dad which are requested later - like:
Wallet += MyDad.GasMoney(REQUEST_MAX_AND_PROMISE_TO_BE_HOME_BY_10PM) ;
But they don't have a reference to Dad, so they won't be able to do that. So I would have the CChild constructor take a this reference, too.
class ICashProvider {
public:
virtual money Request(IPerson,CashRequestFlags) ;
};
class IChaffeur {
public:
virtual void Drive(IPerson[]) ;
};
etc.
And then CChild constructor would need to take ICashProvider and IChaffeur, as would CWife and CGirlfriend (and CBoyfriend, perhaps). At this point, I think you might realize that this level of granularity is pointless in the face of Dad's responsibilities and you just give everyone this and have Dad authenticate requests by forcing callers to send their own this on some methods, so you don't have Dad performing incest or changing the CWife's diaper.
|
491,994
| 492,086
|
Is it possible to treat a template instance as a namespace?
|
Suppose I have
template< unsigned int num >
class SomeFunctionality
{
static unsigned int DoSomething()
{
//...
}
static void DoSomethingElse()
{
}
};
typedef SomeFunctionality<6> SomeFunctionalityFor6;
Semantically, "SomeFunctionalityFor6" is essentially a namespace specific to the template argument, 6. So in the code using this instance of the template instead of doing
int main()
{
SomeFunctionalityFor6::DoSomething();
}
I'd rather have the ability to use a "using" statement ala a real namespace
int main()
{
using SomeFunctionalityFor6;
DoSomething();
}
This, as I would suspect doesn't work. Visual studio complains that it wants a namespace defined by the "namespace" keyword following any using statement.
Is there anyway to do what I'm trying to do? Mainly I just don't want to fully qualify the namespace everytime I call the static methods. I know its mostly just syntactic sugar, but in my opinion it can make code much more readable. I'm wondering if there's even ways to templatize a namespace directly instead of having to use the "class" keyword.
|
You can't do that. Neither templatized namespace, nor using class_name.
The only places in the code that can use static functions from a class without qualification are derived classes.
In your case, I would use a typedef for some short name, like
int main()
{
typedef SomeFunctionalityFor6 SF6;
SF6::DoSomething();
}
|
492,014
| 492,392
|
How to start writing a PHP5 extension in C++
|
I'm writing a PHP5 extension, and while I could write it in C, it would be easier to use C++ and take advantage of the STL and Boost.
Trouble is, the tutorials I've seen only deal with C, and I'm looking for a basic example which uses C++
Here's what I've tried so far:
config.m4
[ --enable-hello Enable Hello World support])
if test "$PHP_HELLO" = "yes"; then
AC_DEFINE(HAVE_HELLO, 1, [Whether you have Hello World])
PHP_NEW_EXTENSION(hello, hello.cpp, $ext_shared)
fi
php_hello.h
Note my attempt to declare the bits that PHP interfaces with as extern "C"
#ifndef PHP_HELLO_H
#define PHP_HELLO_H 1
extern "C" {
#define PHP_HELLO_WORLD_VERSION "1.0"
#define PHP_HELLO_WORLD_EXTNAME "hello"
PHP_FUNCTION(hello_world);
extern zend_module_entry hello_module_entry;
#define phpext_hello_ptr &hello_module_entry
}
#endif
hello.cpp
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_hello.h"
static function_entry hello_functions[] = {
PHP_FE(hello_world, NULL)
{NULL, NULL, NULL}
};
zend_module_entry hello_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
PHP_HELLO_WORLD_EXTNAME,
hello_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
#if ZEND_MODULE_API_NO >= 20010901
PHP_HELLO_WORLD_VERSION,
#endif
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_HELLO
ZEND_GET_MODULE(hello)
#endif
PHP_FUNCTION(hello_world)
{
RETURN_STRING("Hello World", 1);
}
....and here are my build errors:
If I phpize, configure and make this, I get the following (reformatted for clarity)
$ make
/bin/bash /home/paul/php5/php-5.2.8/ext/hello2/libtool
--mode=compile
-I.
-I/home/paul/php5/php-5.2.8/ext/hello2 -DPHP_ATOM_INC
-I/home/paul/php5/php-5.2.8/ext/hello2/include
-I/home/paul/php5/php-5.2.8/ext/hello2/main
-I/home/paul/php5/php-5.2.8/ext/hello2
-I/usr/local/include/php
-I/usr/local/include/php/main
-I/usr/local/include/php/TSRM
-I/usr/local/include/php/Zend
-I/usr/local/include/php/ext
-I/usr/local/include/php/ext/date/lib
-DHAVE_CONFIG_H
-c /home/paul/php5/php-5.2.8/ext/hello2/hello.cpp
-o hello.lo
libtool: compile: unrecognized option `-I.'
libtool: compile: Try `libtool --help' for more information.
make: *** [hello.lo] Error 1
I suspect I need more work doing to the config.m4 in order to create a working makefile but I'm pretty new to the GCC toolchain.
If it helps, I'm only targetting php 5.2.6+, and only on Linux (specifically, Ubuntu 8.04). My build environment is using Ubuntu 8.10, using gcc 4.3.2
Pointers gratefully received!
|
After posting I came across CodeGen_PECL which creates a skeleton extension from an XML based description of the extension. This includes a tag make it output C++
As well as making sure the header file used extern "C", the generated cpp file also ensured the ZEND_GET_MODULE(hello) was inside an extern "C" block also.
As expected, the biggest difference was in the m4 file, which looked like this:
dnl
dnl $ Id: $
dnl
PHP_ARG_ENABLE(hello, whether to enable hello functions,
[ --enable-hello Enable hello support])
if test "$PHP_HELLO" != "no"; then
PHP_REQUIRE_CXX
AC_LANG_CPLUSPLUS
PHP_ADD_LIBRARY(stdc++,,HELLO_SHARED_LIBADD)
export OLD_CPPFLAGS="$CPPFLAGS"
export CPPFLAGS="$CPPFLAGS $INCLUDES -DHAVE_HELLO"
AC_MSG_CHECKING(PHP version)
AC_TRY_COMPILE([#include <php_version.h>], [
#if PHP_VERSION_ID < 40000
#error this extension requires at least PHP version 4.0.0
#endif
],
[AC_MSG_RESULT(ok)],
[AC_MSG_ERROR([need at least PHP 4.0.0])])
export CPPFLAGS="$OLD_CPPFLAGS"
PHP_SUBST(HELLO_SHARED_LIBADD)
AC_DEFINE(HAVE_HELLO, 1, [ ])
PHP_NEW_EXTENSION(hello, hello.cpp , $ext_shared)
fi
So, if you're struggling with the same problem, use CodeGen_PECL, or adapt the m4 sample above (as well as making sure you've used extern "C" in your header and around the ZEND_GET_MODULE macro)
|
492,061
| 492,112
|
Why doesn't std::string provide implicit conversion to char*?
|
std::string provides const char* c_str ( ) const which:
Get C string equivalent
Generates a null-terminated sequence
of characters (c-string) with the same
content as the string object and
returns it as a pointer to an array of
characters.
A terminating null character is
automatically appended.
The returned array points to an
internal location with the required
storage space for this sequence of
characters plus its terminating
null-character, but the values in this
array should not be modified in the
program and are only granted to remain
unchanged until the next call to a
non-constant member function of the
string object.
Why don't they just define operator const char*() const {return c_str();}?
|
From the C++ Programming Language 20.3.7 (emphasis mine):
Conversion to a C-style string could have been provided by an operator const char*() rather than c_str(). This would have provided the convenience of an implicit conversion at the cost of surprises in cases in which such a conversion was unexpected.
|
492,091
| 492,143
|
C++ scanner (string-fu!)
|
I'm writing a scanner as part of a compiler.
I'm having a major headache trying to write this one portion:
I need to be able to parse a stream of tokens and push them one by one into a vector, ignoring whitespace and tokenizing special symbols (simple case, lets just consider parentheses and braces)
Example:
int main(){ }
should parse into 6 different tokens:
int
main
(
)
{
}
How would you go about solving this? I'm writing this in C++, but a java/C# solution would be appreciated as well.
Some points:
and no, I can't use Boost, I can't guarantee that the libraries will be
available to me. (don't ask...)
I don't want to use lex, or any other special tools. I've never done
this before and just want to try this once to say I've done it.
|
Stroustrup's book, The C++ Programming Language, has a great example in it about building a lexer/parser for a simple calculator program. It should serve as a good starting point to learn how to do what you want.
|
492,286
| 492,378
|
Free static code scanner for C/C++/C#
|
Does anyone know an open-source and/or free code-scanner for automated code analysis in C#, C or C++?
I know for Java there's some brilliant stuff like FindBugs (Eclipse integrated), PMD, or Hammurapi.
Is there anything similar for the C-languages?
wishi
|
For .NET languages, you can look at Reflector CodeMetrics which provides some code analysis and design metrics. Also take a look at all of the Reflector addins.
I also second the recommendation for FxCop and StyleCop.
|
492,307
| 1,499,819
|
Uploading big files over HTTP
|
I need to upload potentially big (as in, 10's to 100's of megabytes) files from a desktop application to a server. The server code is written in PHP, the desktop application in C++/MFC. I want to be able to resume file uploads when the upload fails halfway through because this software will be used over unreliable connections. What are my options? I've found a number of HTTP upload components for C++, such as http://www.chilkatsoft.com/refdoc/vcCkUploadRef.html which looks excellent, but it doesn't seem to handle 'resume' of half done uploads (I assume this is because HTTP 1.1 doesn't support it). I've also looked at the BITS service but for uploads it requires an IIS server. So far my only option seems to be to cut up the file I want to upload into smaller pieces (say 1 meg each), upload them all to the server, reassemble them with PHP and run a checksum to see if everything went ok. To resume, I'd need to have some form of 'handshake' at the beginning of the upload to find out which pieces are already on the server. Will I have to code this by hand or does anyone know of a library that does all this for me, or maybe even a completely different solution? I'd rather not switch to another protocol that supports resume natively for maintenance reasons (potential problems with firewalls etc.)
|
I'm eight months late, but I just stumbled upon this question and was surprised that webDAV wasn't mentioned. You could use the HTTP PUT method to upload, and include a Content-Range header to handle resuming and such. A HEAD request would tell you if the file already exists and how big it is. So perhaps something like this:
1) HEAD the remote file
2) If it exists and size == local size, upload is already done
3) If size < local size, add a Content-Range header to request and seek to the appropriate location in local file.
4) Make PUT request to upload the file (or portion of the file, if resuming)
5) If connection fails during PUT request, start over with step 1
You can also list (PROPFIND) and rename (MOVE) files, and create directories (MKCOL) with dav.
I believe both Apache and Lighttpd have dav extensions.
|
492,475
| 493,224
|
Inline ostringstream macro reloaded
|
Referring to C++ format macro / inline ostringstream
The question there was for a macro that allows inline concatenation of objects to create a string, iostream-style.
The answer was:
#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
( std::ostringstream().seekp( 0, std::ios_base::cur ) << x ) \
).str()
Usage (for example):
throw std::runtime_error(
SSTR( "FooBar error: Value " << x << " exceeds " << y )
);
That works beautifully - with GCC. It compiles and runs under Visual C++ 2005, too. But with the latter, all uses of the macro result in empty strings, and I am quite dumbfounded as to why, and how to fix it...?
|
Unfortunately I don't have access to a MSVC compiler to test against.
In my past experiences with microsoft's tools, it seems like microsoft treats language definitions and standards as little more than a rough guide. (I've lost lots of time on projects only to discover microsoft broke tradition with something as basic as C99.)
Given this regrettably situation, I suggest you experiment with a series of trivial programs. Things like:
std::ostringstream() o;
o.seekp( 0, std::ios_base::cur ) << "foo";
cout << "Test1: " << o << endl;
Or perhaps:
std::ostringstream() o;
cout << "Test2: " << typeid(o).name() << endl;
cout << "Test3: " << typeid(o.seekp( 0, std::ios_base::cur )).name() << endl;
Try to see at what point things stop working. Then work around the problem from there.
|
492,741
| 492,767
|
Java: No interface implementation?
|
Today I got my book "Head First Design Patterns" in the mail. Pretty interesting stuff so far, however I do have a question about it's contents.
I have no Java/C# background nor do I wish to jump into those languages right now (I'm trying to focus on C++ first). In the book is said that java does not have an implementation for interfaces... This would mean that for every change to that interface, you would have to modify all subclasses that implement the interface.
How is this done in C++? What am I missing?
|
What the author of the book meant, if you change the signatures of the members of the interface or add new ones, you will need to make those changes in the implementing classes as well so that they keep implementing the interface.
You can change the implementing classes whatever way you want as long you have the members of the interface implemented with exactly the same signatures (that is, with the same name, return type, and the order and type of parameters).
I have the impression that you don't quite understand how interfaces work, so I suggest reading up the C# interface specification on MSDN which is quite clear on the subject I think (and it's pretty much the same in Java except that in Java you use the "implements" keyword instead of a colon (:) to declare that a class implements a specific interface).
|
492,916
| 492,925
|
Best way to monitor disk mounts in Linux using C++?
|
I am currently constructing a Carputer front end and one function that it needs is to be able to recognize when external media is inserted, such as USB/SD memory sticks or iPods. Upon their insertion, I will then scan the device for music/video/images and add them to the media library. Alternately, I need to know when these devices are removed so that I can remove the added items from the currently available media.
My question is, what is the best way to monitor disk insertions/removals in a Linux environment using C++?
I could monitor the /media folder for when Linux mounts the disks automagically, but is this the best way to accomplish the task? Thanks for any insight!
|
You can read kernel uevents from a NetLink socket. It provides events about device adding/removal, mount/umount.
-- Netlink
A daemon listening to the netlink
socket receives a packet of data for
each hotplug event, containing the
same information a usermode helper
would receive in environment
variables.
The netlink packet contains a set of
null terminated text lines. The first
line of the netlink packet combines
the $ACTION and $DEVPATH values,
separated by an @ (at sign). Each
line after the first contains a
KEYWORD=VALUE pair defining a hotplug
event variable.
[...]
ACTION
The current hotplug action: "add" to add the device, "remove" to remove
it. The 2.6.22 kernel can also generate "change", "online",
"offline", and "move" actions.
You probably want to monitor mount and umount actions. Note that event does not give you either device node or the actual mount point, only device's sysfs node. If device nodes management and mounts management are handled by an external process (e.g. udev), you'll have to find out the device node and a mount point yourself using major and minor device numbers and /proc/mounts.
|
492,953
| 493,192
|
Calling PowerShell scripts from unmanaged C++
|
Microsoft appears to be moving a lot of configuration and query capabilities to PowerShell (accessible from C# or managed C++), while deprecating and even removing older APIs (accessible for C or unmanaged C++). Those of us who have extensive unmanaged C++ programs that can't switch to managed C++ may have a need to call PowerShell cmdlets (at least, I have one now) -- how can we do so?
There are suggestions that a reverse-PInvoke (managed/unmanaged thunking) might be able to do something, but I'm hoping for a better way than either thunking or parsing text output from a PowerShell script.
[Note: This is a reworked and generalized query I made yesterday that may have been too specialized.]
|
The MS suggestion would probably be to compile specific classes/modules in your generally unmanaged C++ app as managed code (compiling individual files with /clr), and letting the IJW transition code manage the calls to/from it (and calling PowerShell API's from the managed bits). I've been told (from MS VC++ people) that's the expected methodology for adding bits of managed calls to large unmanaged applications.
Hope that helps.
|
493,194
| 493,294
|
What do I need to compile the kernel on Ubuntu Eee?
|
I'm trying follow a tutorial to create a custom USB driver in Linux and I hope to develop this thing on my Eee PC with Ubuntu Eee using g++. Unfortunately to follow the tutorial I need the linux/module.h header file. From what I understand I will need to compile the kernel to get this to work. I never compiled a kernel before and all of the instructions I find are for the desktop Ubuntu.
I am doing this on my Eee since I will get extra credit in a class if I can do this and use it in a class project.
The tutorials that I am following is here: http://www.linuxjournal.com/article/7353 and here: http://www.linuxjournal.com/article/4786
|
Most (All?) of the major Linux distros not only distribute the linux kernel, but also apply numerous patches to it. Thereby improving stability and adding lots of features. So you'll want to use Ubuntu's package system to grab down Ubuntu's patched kernel source!
You probably do NOT need to rebuild the kernel! Most likely, you just need the kernel-headers package for your current kernel to compile your USB driver. Assuming you are building it as a kernel module, you can then load it with modprobe or insmod. (lsmod & rmmod are also useful.)
If you do need to rebuild the kernel, well, it's easy. (So easy, I use kernel builds to test my hardware.) There's lots of Kernel Building HOWTO's on the web. You're in for a lot of fun trying to figure out what options you want as modules, what you want compiled in, and what you want to leave out. You can make the kernel smaller, but you might miss some of that stuff.
Amended to add:
I remember doing "sudo apt-get install linux-headers-eeepc," do I need more than that? If not then where are those headers because my test code that includes "linux/module.h" doesn't compile
There should be a way to list all the files in that linux-headers-eeepc package. I'm coming from the RedHat/RPM world. But I would guess something like dpkg --contents linux-headers-eeepc or dpkg --listfiles linux-headers-eeepc. You may have to play around with that a bit.
Alternatively, judging by http://packages.ubuntu.com/, packages like linux-headers-2.6.27-7 contain the file /usr/src/linux-headers-2.6.27-7/include/linux/module.h. So you might just want to look around in /usr/src/*/include/linux/module.h.
Alternatively, try:
% locate linux/module.h | grep 'linux/module.h$'
Or
% find / -path '*/linux/module.h'
(That find might take a while to complete...)
|
493,200
| 493,217
|
Creating XML in C++ Code
|
In my project there are situations where we have to send xml messages (as char *) among modules. They are not really large ones, just 10-15 lines. Right now everybody just creates the string themselves. I dont think this is the right approach. We are already using xerces DOM library. So why not create a Dom tree, serialize it, and then send it.
What do you guys suggest?
|
If you are really just creating small XML messages, Xerces is an overkill, IMHO. It is a parser library and you are not parsing anything.
|
493,401
| 493,547
|
How the C++0x standard defines C++ Auto multiple declarations?
|
mmm, I have just a little confusion about multiple auto declarations in the upcoming C++0x standard.
auto a = 10, b = 3.f , * c = new Class();
somewhere I read it is not allowed.
The reason was(?) because it was not clear if the consecutive declarations should have the same type of the first one , (int in the example) , or not.
Possible translation 1:
int a = 10;
int b = 3.f;
int * c = new Class ();
causing an error
Possible translation 2:
int a = 10;
float b = 3.f;
Class * c = new Class ();
how it is resulted in the standard?
If I can say my POV, translation #2 was the most obiouvs, at least for me that I'm a regular C++ user . I mean, for me "every variable declared is of the same declared type", witch is auto.
Translation #1 would be really un-intuitive to me.
Good Bye
QbProg
|
It's probably not the latest, but my C++0x draft standard from June 2008 says you can do the following:
auto x = 5; // OK: x has type int
const auto *v = &x, u = 6; // OK: v has type const int*, u has type const int
So unless something has changed from June this is (or will be) permitted in a limited form with a pretty intuitive interpretation.
The limitation is that if you do want to string multiple auto declarations like this (using the example above), it works because the inferred type of v and u have the same 'base type' (int in this case) to use an inexact term.
If you want the precise rule, The draft standard says this:
If the list of declarators contains more than one declarator, the type of each declared variable is determined as described
above. If the type deduced for the template parameter U is not the same in each deduction, the program is ill-formed.
where the "deduced template parameter U" is determined by:
the deduced type of the parameter u in the call f(expr) of the following invented function template:
`template <class U> void f(const U& u);`
Why they've come up with this rule instead of saying something like:
auto a = 10, b = 3.f , * c = new Class();
is equivalent to:
auto a = 10;
auto b = 3.f;
auto * c = new Class();
I don't know. But I don't write compilers. Probably something to do with once you've figured out the the auto keyword replaces, you can't change it in the same statement.
Take for example:
int x = 5;
CFoo * c = new CFoo();
auto a1 = x, b1 = c; // why should this be permitted if
int a2 = x, CFoo* b2 = c; // this is not?
In any case, I'm not a fan of putting multiple declarations on the same statement anyway.
|
493,447
| 493,496
|
Should I use GetProcAddress or just include various win32 libraries?
|
Wonder what the difference between:
static PROCESSWALK pProcess32First=(PROCESSWALK)GetProcAddress(hKernel,"Process32First");
...
pProcess32First(...);
what is hKernel? Look in here. You can replace with GetModuleHandle()
and
#include <Tlhelp32.h>
...
Process32First(...);
What are the differences, I wonder which I should use. Is there any difference in terms of best practices then?
|
NOTE: my answer assumes that the function is available either way, there are other things to consider if you are after non-exported functions.
If you use LoadLibrary and GetProcAddress, then you have the option running with reduced functionality if the required library isn't there. if you use the include and link directly the lib, and dll isn't there (or doesn't have the export due to wrong version) your app will simply fail to load.
It really only makes a difference if you want to use a function that isn't in all versions of a given dll.
|
493,613
| 493,639
|
C++ Project dependencies issue Visual studio 2005
|
I am working on a dataManagement project that periodically deletes files in a specific folder. The solution has three projects of which, one is the application and the other two are static libraries. Now I want to add one more project which is a static library used for logging. The logging static library project has a header file which the application project refers. When I build the solution, I am getting error as the header file is not found. When I added the logging static library project, I also made the application project dependent on it by checking the appropriate bix in the project dependencies.
Can anyone please help me?
|
It needs an additional include file path to reference the header file directory...
Project->Properties->Config Properties->C/C++->Additional Include Directories
it doesn't auto pick up the header file paths, it just knows how to link to the project.... Its completely undefined where the header file should be. or even if you have a header file, you can forward reference the thing in the other project if you like!
|
493,774
| 493,868
|
Why don't the standard C++ container adaptors provide a clear function?
|
Does anyone know why std::queue, std::stack, and std::priority_queue don't provide a clear() member function? I have to fake one like this:
std::queue<int> q;
// time passes...
q = std::queue<int>(); // equivalent to clear()
IIRC, clear() is provided by everything that could serve as the underlying container. Is there a good reason to not have the container adaptors provide it?
|
Well, I think this is because clear was not considered a valid operation on a queue, a priority_queue or a stack (by the way, deque is not and adaptor but a container).
The only reason to use the container
adaptor queue instead of the container
deque is to make it clear that you are
performing only queue operations, and
no other operations. (from the sgi page on queue)
So when using a queue, all you can do is push/pop elements; clearing the queue can be seen as a violation of the FIFO concept. Consequently, if you need to clear your queue, maybe it's not really a queue and you should better use a deque.
However, this conception of things is a little narrow-minded, and I think clearing the queue as you do is fair enough.
|
493,985
| 495,510
|
C++ compiler unable to find function (namespace related)
|
I'm working in Visual Studio 2008 on a C++ programming assignment. We were supplied with files that define the following namespace hierarchy (the names are just for the sake of this post, I know "namespace XYZ-NAMESPACE" is redundant):
(MAIN-NAMESPACE){
a bunch of functions/classes I need to implement...
(EXCEPTIONS-NAMESPACE){
a bunch of exceptions
}
(POINTER-COLLECTIONS-NAMESPACE){
Set and LinkedList classes, plus iterators
}
}
The MAIN-NAMESPACE contents are split between a bunch of files, and for some reason which I don't understand the operator<< for both Set and LinkedList is entirely outside of the MAIN-NAMESPACE (but within Set and LinkedList's header file).
Here's the Set version:
template<typename T>
std::ostream& operator<<(std::ostream& os,
const MAIN-NAMESPACE::POINTER-COLLECTIONS-NAMESPACE::Set<T>& set)
Now here's the problem: I have the following data structure:
Set A
Set B
Set C
double num
It's defined to be in a class within MAIN-NAMESPACE. When I create an instance of the class, and try to print one of the sets, it tells me that:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const MAIN-NAMESPACE::POINTER-COLLECTIONS-NAMESPACE::Set' (or there is no acceptable conversion)
However, if I just write a main() function, and create Set A, fill it up, and use the operator- it works.
Any idea what is the problem? (note: I tried any combination of using and include I could think of).
|
OK I figured this out.
jpalecek's intuition about there existing another operator<< in the namespace was correct (apparently I forgot to comment it out).
The lookup rules for namespaces first start the search in the function call's namespace and search up the enclosing namespaces, right up to the global namespace (then it does the Argument dependent lookup if no match is found). However, if along the way it finds some match for operator<<, it stops the search, regardless of the fact that the types used in those functions may be incompatible, as was the case here.
The solution is either to include it into the MAIN-NAMESPACE (which I'm not allowed to), or import it from the global namespace with "using ::operator<<".
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.