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 |
|---|---|---|---|---|
4,663,290 | 4,663,397 | C++ POSIX (or Linux specific) and WIN32 calls for artificially changing a file's creation date | To start: My code depends on Boost.
I need to alter file creation dates to inject errors into my unit tests.
Is there a portable way, either in the STL, or C++ standard libraries, or boost(::filesystem), to do this ? If not does anyone know of a good simple C++ header-only (or very simple) abstraction that will complem... | The POSIX solution would be utimes.
#include <sys/time.h>
int utimes(const char *filename, const struct timeval times[2]);
The win32 solution would be SetFileTime.
|
4,663,291 | 4,705,764 | Android NDK R5 and support of C++ exception | I am trying to use the NDK 5 full C++ gnustl:
The CPLUSPLUS-SUPPORT.html states:
The NDK toolchain supports C++ exceptions, since NDK r5, however all C++
sources are compiled with -fno-exceptions support by default, for
compatibility reasons with previous releases.
To enable it, use the '-fexceptions' C++ compiler... | It turns out that exceptions work but only if the exception are inherited from std::exception. In my case the exception hierarchy did not always include std::exception which broke the catch/throw. Curiously the throwing strings as exceptions works when compiled for x86/Mac OS. I have fixed my problem by modifying the e... |
4,663,395 | 4,663,629 | specific syntax question |
Is it possible to create template to the initialization like:
template <typename C> typename C::value_type fooFunction(C& c) {...};
std::vector<string> vec_instance;
fooFunction(cont<0>(vec_instance));
fooFunction(cont<1>(vec_instance));
In general i'm interested is it possible to specify template using integer (ie.... | I'm not completely clear on what you're asking, but the following snippet works for me:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template <typename C>
typename C::value_type fooFunction(const C & c) { return 0; };
/* note that fooFunction takes a ref-to-const, not a reference */ ... |
4,663,455 | 4,663,473 | Why is erase() function so expensive? | Consider a 2d vector vector < vector <int> > Nand lets say its contents are as follows:
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
So the size of N here is 4 i.e. N.size() = 4
Now, consider the following code :
int i = 0;
while(N != empty()){
N.erase(i);
++i;
}
I calculated the time just for this piece of code alone with variou... | Consider what happens when you delete the first element of a vector. The rest of the vector must be "moved" down by one index, which involves copying it. Try erasing from the other end, and see if that makes a difference (I suspect it will...)
|
4,663,579 | 4,663,619 | Visual Studio store hidden data in the compiled files? | I want to know if Visual Studio store hidden data in compiled files ( or other files ).
I am talking about information data about the fact that the program is written with Visual Studio.
| Visual Studio itself does not watermark your programs in this way, but it is often detectable that you used Microsoft's toolchain simply because of incidentals, i.e. what order methods are compiled into the file, what implementation of exceptions is used (MSVC++ uses a specific exception code on top of NT's SEH in orde... |
4,663,792 | 4,663,976 | Copying to binary file row of a matrix | I want to write each row of a matrix to a binary file.
I try writing it like this:
vector< vector<uint32_t> > matrix;
...
for(size_t i = 0; i < matrix.size(); ++i)
ofile->write( reinterpret_cast<char*>(&matrix[i]), sizeof(uint32_t*sizeof(matrix[i])) );
{
for(size_t j = 0; j < numcols; ++j)
{
std::cout... | In case interjay's guidelines weren't enough:
vector< vector<uint32_t> > matrix;
for(size_t i = 0; i < matrix.size(); ++i)
ofile.write( (char*)&matrix[i][0], sizeof(matrix[i][0])*matrix[i].size() );
Out-of-context question: Why is ofile a pointer? (certainly don't need to be in this example)
|
4,663,966 | 4,664,201 | undefined reference to WinMain@16 when using boost with MinGW | I'm programming in C++ with Eclipse under Windows 7.
My makefile is as follows:
build:
g++ -shared -o "lib\libCacheOpt.a" "src\*.cpp" -enable-auto-import -I"${CWD}\include" -I"${BOOST}" -L"${BOOST}\lib" -lboost_program_options -lboost_unit_test_framework
exec: build
g++ "src\main.cpp" -enable-auto-import -I"${... | It looks like you don't have a main method. You can create one using BOOST_TEST_MAIN. BOOST_TEST_MODULE only defines main if and only if BOOST_TEST_DYN_LINK is already defined.
|
4,663,991 | 4,664,134 | Pointless 'MIDL_INTERFACE' Macro in winapi? | After browsing some old code, I noticed that some classes are defined in this manner:
MIDL_INTERFACE("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
Classname: public IUnknown {
/* classmembers ... */
};
However, the macro MIDL_INTERFACE is defined as:
#define MIDL_INTERFACE(x) struct
in C:/MinGW/include/rpcndr.h (somewh... | In the Windows SDK version that macro expands to
struct __declspec(uuid(x)) __declspec(novtable)
The first one allows use of the __uuidof keyword which is a nice way to get the guid of an interface from the typename. The second one suppresses the generation of the v-table, one that is never used for an interface. A... |
4,664,125 | 4,673,710 | How to serialize fusion::vector? | Tell me, how can I serialize/deserialize the fusion::vector object type?
Thanks.
| Solved.
Like this: http://liveworkspace.org/code/652cab59dc33d280b6d48470c11cfb91
#include <iostream>
#include <sstream>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/include/vector.hpp>
#include... |
4,664,187 | 4,664,671 | Converting cv::Mat to IplImage* | The documentation on this seems incredibly spotty.
I've basically got an empty array of IplImage*s (IplImage** imageArray) and I'm calling a function to import an array of cv::Mats - I want to convert my cv::Mat into an IplImage* so I can copy it into the array.
Currently I'm trying this:
while(loop over cv::Mat array... | cv::Mat is the new type introduce in OpenCV2.X while the IplImage* is the "legacy" image structure.
Although, cv::Mat does support the usage of IplImage in the constructor parameters, the default library does not provide function for the other way. You will need to extract the image header information manually. (Do re... |
4,664,277 | 4,677,791 | Create a cursor from .cur format bytes? | I can find a couple ways to create a cursor in win32 but I need the third, the one I can't find.
The first I can find is to use LoadXXX() to open a file or resource and load the cursor that way.
The second I can find is to use CreateCursor to take the hot-spot points, some data arrays, and make one out of bits.
I want ... | Can't be done. Best not to waste time trying. I was only trying to avoid having to convert a bunch of .cur files to something that sensible libraries support. Thought I'd use the HCURSOR constructor for QCursor, and I could, but it's just not worth the f'n bother trying to work around the worse imaginable API when I... |
4,664,300 | 4,664,761 | C++ NetBeans: How to link my .o file to my project? | I've bought a class. I have the header (.h) and an object-file (.o).
How do I link the .o file in my NetBeans IDE ?
Thanks!
| You need to add your .o file as an external library. I was able to accomplish this using the following steps:
Go to Project Properties
Under the Build->Linker options, add a library to the Libraries section
Click 'Add Library File'
Navigate to your .o file and select the absolute path option
Rebuild
Hopefully this w... |
4,664,899 | 4,664,910 | Wrapping C/C++ inside Java | I develop applications/programs in C/C++. I am more versed in these two languages and love being a C++ developer. I am wondering how to create a Java program that contains all my C++ code.
I mean, I would like to wrap all my C++ code (that is already developed) inside Java class. But clueless how to do it.
Please post... | If you want to call C++ from Java, you'll need to use JNI - Java Native Interface.
Be warned that you lose some of the benefits of the garbage collector, since it can't deal with your C++ objects, and your code won't be portable anymore.
Maybe you'd be better served by learning to write 100% Java and leaving C++ be... |
4,665,117 | 4,665,163 | C++ virtual function return type | Is it possible for an inherited class to implement a virtual function with a different return type (not using a template as return)?
| In some cases, yes, it is legal for a derived class to override a virtual function using a different return type as long as the return type is covariant with the original return type. For example, consider the following:
class Base {
public:
virtual ~Base() {}
virtual Base* clone() const = 0;
};
class Derive... |
4,665,150 | 4,673,113 | How to add a folder with multiple libs and a folder with multiple headers into your project with Qt? | So my problem is next: I need to connect to my project Boost, FFMpeg, OpenCV and OpenAL. I have putted all .lib files for tham into some C://libs/ and headers and additional source into C://headers/ and C://src/ so I have this 3 folders I will need to cnnect to my project... I am so very new to qt and I am starting t... | For the header files, add the path to the folders to the INCLUDEPATH variable:
INCLUDEPATH += C:/headers/
For the libraries, add them to your LIBs as in your example. You may need to do this one-by-one, or you could set something up for qmake to process the directory and add the given files.
LIBS +=C:/Qt/2010.02.1/qt... |
4,665,231 | 4,665,550 | How to specialize this template (paying attention to return type) | I'd like to specialize following template:
template <typename T, int P>
T item(size_t s);
into something like that:
template<int P>
T item<typename T>(size_t s)
{
//for all numeric types
return static_cast<T>(rand());
}
template <int P>
string item<string>(size_t s)
{
return "asdf";
}
| Both are going to require partial specialization. The first is going to require SFINAE. Since function templates can only be fully specialized you'll have to use a helper object of some sort.
template <typename T, int P>
T item(size_t s);
template < typename T, typename Enable = void >
struct item_
{
template < in... |
4,665,264 | 4,665,272 | The namespace starts with :: in C++ |
Possible Duplicate:
What's the purpose of a leading “::” in a C++ method call
This gtest has the example code.
::testing::AssertionResult IsEven(int n) {
if ((n % 2) == 0)
return ::testing::AssertionSuccess();
else
return ::testing::AssertionFailure() << n << " is odd";
}
How does it work? If the namesp... | The :: prefix refers to the global namespace, so this is like an absolute versus relative path specification.
|
4,665,569 | 4,665,620 | Safest way to change variable names in a project | So I've been working on a relatively large project by myself, and I've come to realise that some of the variable names earlier on were.. less than ideal.
But how does one change variable names in a project easily? Is there such a tool that can go through a project directory, parse all the files, and then replace the va... | Safest (non automated way) way:
Make sure all your unit tests work.
Save everything into source control.
Globally replace var with XXXvarXXX (seriously)
a. Or maybe just the files you think need editing.
Try and compile. Everything that does not compile is easy to undo just remove the XXX.
When it compiles run t... |
4,665,602 | 4,665,617 | Is it possible to have polymorphic member overloading in C++? | I have been working on a Roguelike, and run into a problem with it. My problem is that I would like to use "polymorphic overloading" or sorts, but I'm guessing C++ doesn't support.
My class diagram is like this:
xMapObject <- xEntity <- xVehicle
An the problem is, it is possible to have this:
class xMapObject
{
publ... | Sure it works. I think though that you expect it to be able to tell the difference when you pass it an xMapObject* and that simply won't happen.
You need a double dispatch mechanism. Perhaps visitor but I'm doubting it. See Modern C++ Design or wiki for multimethods.
|
4,665,603 | 4,665,628 | Calling a method on a map from another method | // Penguin.h
#include <map>
#include <iostream>
class Penguin
{
typedef void (Penguin::*PenguinMet)();
std::map<int, PenguinMet> Methods;
void Move();
int p;
public:
Penguin();
void Walk();
};
Penguin::Penguin()
{
p = 0;
Methods[0] = &Penguin::Move;
}
void Penguin::Move()
{
... | You're not actually calling the function, you're just looking at the value of the member function pointer as a void expression, which has no effect. Change Penguin::Walk to this:
void Penguin::Walk()
{
(this->*Methods[p])();
(*this.*Methods[p])();
}
That way you're actually calling the method and passing in t... |
4,665,726 | 4,665,774 | Is this bad practice? C++ | Class1 myclass(someparameter);
int main(int argc, char* argv[])
{
myclass = Class1(anotherparameter);
}
I have a variable at file scope.
I don't really know how to word my question. But basically I am copying a class and this code looks quite funky. Are there any consequences of doing this? Should I use new / del... | Assuming your class can correctly copy, then I don't see anything inherently wrong with this. But it's not all that efficient since myclass is actually initialized twice: once where it's declared, and again where you assign another instance to it.
If that's what your logic requires, it's okay. Otherwise, you could make... |
4,665,760 | 4,666,100 | Help simplifying a Makefile for multiple executables | I have common code (e.g. hello.cpp) that is used by multiple executables. I'm using a single Makefile to build it all:
EXE=app1.out app2.out
SRC=hello.cpp
OBJ=$(SRC:.cpp=.o)
SRC_MAIN=app1.cpp app2.cpp
OBJ_MAIN=$(SRC_MAIN:.cpp=.o)
all: $(EXE)
app1.out: app1.o $(OBJ)
g++ $< $(OBJ) -o $@
app2.out: app2.o $(OB... | The problem appears to be that you are using old-style suffix rules. From the make info:
Suffix rules cannot have any prerequisites of their own. If they
have any, they are treated as normal files with funny names, not as
suffix rules. Thus, the rule:
.c.o: foo.h
$(CC) -c $(CFLAGS) $(CPPFLAGS) -o ... |
4,665,808 | 4,665,984 | How can I output erasable text in c++ to console? | I remember seeing completed programs where you could backspace and delete text prompts. Usually, all text that is cout'ed is static and cannot be erased from the screen, but I want to be able to erase text that was output by the program (such as, for example, the program gives me a default name that I can accept, or de... | If I understand you, you probably want something like GNU Readline
"The GNU Readline library provides a
set of functions for use by
applications that allow users to edit
command lines as they are typed in.
Both Emacs and vi editing modes are
available. The Readline library
includes additional functions to
... |
4,665,832 | 4,665,858 | C++, random number w/ range of 1-6 | I was wondering what the way is to get a random number with a range of 1-6, using the rand() method. This is to simulate a dice roll needed for me to find the average of 3 dice rolls so the type will be double.
| This is a simple example to generate randoms between 1 to 6, I think you can figure the rest
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(0));
std::cout << (rand() % 6 + 1) <<std::endl;
return 0;
}
|
4,665,833 | 4,665,906 | inotify stops monitoring file when the file is deleted and created again | I encounter some problem when using inotify.
I use inotify to monitor changes on files. Here is my code:
int fd = inotify_init();
int wd = inotify_add_watch(fd, "/root/temp", IN_ALL_EVENTS);
int bufSize = 1000;
char *buf = new char[bufSize];
memset(buf, 0, sizeof(buf));
int nBytes = read(fd, buf, bufSize - 1);
cout << ... | That's because inotify monitors the underlying inode, not the filename. When you delete that file, the inode you're currently watching becomes invalid, therefore, you must invoke inotify_rm_watch. If you want to monitor a new file with the same name, but a different inode, you must detect when it's created by monitorin... |
4,665,901 | 4,665,965 | How to call _wsystem without showing console? | I would like to copy a file to a destination by using batch command in my code.
szCommand.Format(_T("copy \"%s\" \"%s\""), szOrg, szTargetFile);
_wsystem(szCommand);
However, each time _wsystem is called, a console window will be prompted, which is very unpleasant.
Is there a way to call _wsystem without showi... | To exert control over how a new program appears, use CreateProcess. Then you can use the CREATE_NO_WINDOW process-creation flag to hide the window of a console program.
But to copy a file from one place to another, skip the external programs and just call CopyFile.
|
4,666,139 | 4,671,466 | How to load qt linguist dynamically changed label text | In my project i'm trying to use qt linguist. When i change the language from English to Turkish, it is working all constant label.
But some labels i m loading them dynamically according to scenario of use cases.
Whatever i do with qt linguist, it doest workthe texts of these label.
How can i get rid of this pr... | Qt has a guide to internationalization, which includes the basic information: to wrap your string in a tr function call.
label->setText( tr( "Hello, World!" ) );
In addition to this, if you want the language to change on the fly, you'll need to identify when the context has changed, and update your labels appropriatel... |
4,666,222 | 4,666,344 | Passing pointer to "class that inherits from A and B" | I have several Abstract Base Classes which act like interfaces as known from Java or C#, let's say these are A, B and C.
Now I have some concrete classes, each implementing a subset of the interfaces:
class Concrete1: public A, public B
class Concrete2: public A, public C
class Concrete3: public A, public C
At some po... | No good alternative exist, I think. Because this problem arose from mistakes at initial interface breakdown.
If its large burden, interfaces redesign is the real good alternative.
Or you could overcome with template method, dynamic_cast, blind C style cast. Or make to two methods for each interfaces.
|
4,666,241 | 4,671,533 | Using wxAny as a container class for wxControls | Can the wxAny class be used to store a wxCheckBox class or other wxControl based classes?
wxPanel *panel = new wxPanel(this, wxID_ANY);
wxCheckBox test(panel, idMenuAbout + 1, wxT("Show title"), wxPoint(20, 20));
wxAny checkBox = test;
The above code generates the error 'wxCheckBoxBase& wxCheckBoxBase::operator=(const... | The problem is not with wxAny but with the fact that wxCheckBoxBase is made non-copyable:
wx/checkbox.h
class WXDLLEXPORT wxCheckBoxBase : public wxControl
protected:
DECLARE_NO_COPY_CLASS(wxCheckBoxBase)
}
wx/defs.h
/* --------------------------------------------------------------------------- */
/* macro ... |
4,666,293 | 4,666,375 | Is there any use in assigning NULL to a pointer after deleting it in destructor in C++? |
Possible Duplicate:
Is it worth setting pointers to NULL in a destructor?
I see some code like this,
void ClassA::~ClassA()
{
delete member;
member = NULL;
}
as the particular instance doesn't exist anymore after this destructor (or the instance is destructed and its members can't be used or dereferenced anymore)... | I see no reason for updating data which is already out of scope, and it is NOT good practice to do things "just in case".
At any rate do not follow "good practices" blindly, it is better to understand why you do things than being the most fervours practitioner of the "good practices" religion.
|
4,666,310 | 4,666,361 | Deleting a dynamically allocated jagged array | I have an array of pointers that point to arrays of ints.
I have made a hard coded array of ints (check 'array' below) and I want to insert it into the array of pointers (check 'bar' below), as far as I can tell, it is still an array of pointers that point to arrays of ints.
It compiles fine; no warnings.
It runs fine;... | The myfunc function takes in a pointer, and then sets bar[0] to that memory address. In your example code, you pass it the address of array, which is an automatic (stack) variable. The destructor then attempts to delete[] bar[0], which points to a stack variable. This is completely undefined behavior, and the reason... |
4,666,450 | 4,666,477 | How does one store a vector<bool> or a bitset into a file, but bit-wise? | How to write bitset data to a file?
The first answer doesn't answer the question correctly, since it takes 8 times more space than it should.
How would you do it ? I really need it to save a lot of true/false values.
| Simplest approach : take consecutive 8 boolean values, represent them as a single byte, write that byte to your file. That would save lot of space.
In the beginning of file, you can write the number of boolean values you want to write to the file; that number will help while reading the bytes from file, and converting... |
4,666,628 | 4,667,273 | Do child threads exit when the parent thread terminates | I was doing some multithreaded programming in Visual studio C++ using the calls beginthreadex, endthreadex.
I create a child thread thread1. The child thread runs on a function which never exits as it has an infinite loop. Now if the parent thread terminates with error or finishes successfully, does the child thread al... | There is no parent/child relationship between threads. If thread A creates thread B and then thread A terminates, then thread B will continue to execute.
The exception to this is when the main thread (that is, the thread that runs the main() function) terminates. When this happens, the process terminates and all other ... |
4,666,849 | 4,668,743 | Call dll with C++ header from C# | I'm trying to call a method in a dll which I have the C++ header for. I'm calling the dll from C#. The input is a string and the output is binary data. Any of the following 3 methods would probably work, I just don't know how to make any of them work all the way.
The C# declaration is made by me, so they might not be c... | The first one ought to be easiest to get going because that leaves it up to the callee to figure out the required size. It is however not obvious how you are supposed to know the size of the allocation. Maybe the return value. You can always pinvoke GlobalSize() to get the size from the HGLOBAL handle. You should p... |
4,667,083 | 4,667,107 | C++ casting question (structs) | In my C++ application I have the definition:
struct socksddr_storage ss;
struct sockaddr *sa;
what is the different between the following:
sa = (struct sockaddr *)&ss;
and
sa = (sockaddr *)&ss;
???
Any help?
| There is no difference in C++ as the struct keyword is optional. In C, the second form is not legal.
|
4,667,141 | 4,674,755 | High delay in RS232 communication on a PXA270 | I'm experiencing a long delay (1.5ms - 9.5ms) in a RS232 communication on a PXA270 RISC PC/104. I want to minimize the long delay but I'm a beginner with embedded devices and C++ so I think I'm missing something.
The mentioned delay is at the time when the PXA board receives a packet from the external device via RS232 ... | Thank you very much for your comments.
I was able to reduce the delay to ~0.4ms. The command setserial(8) was referenced in the AEL manual. And bingo, I found the low_latency flag there with the following description:
Minimize the receive latency of the
serial device at the cost of greater
CPU utilization. (Normal... |
4,667,199 | 8,464,580 | Does anyone know any C/C++ open-source client lib for OpenSocial REST? | I found one for Java and lot others in Obj-C, PHP etc but none in C/C++.
I wanted to use it on Symbian. I know we can use java to develop code on SYmbian, but I want to use C/C++ only.
Thank you!!
| I landed up using QT's http functions.
|
4,667,266 | 4,668,788 | C++ name mangling by hand | I am writing a script for the IDA Pro disassembler in Python using the idapython plugin. Using this, I am able to fill in the gaps where IDA's auto-analysis falls short.
One area that has me stumped is naming locations/functions with (for want of a better term) "pretty names". An example of what I mean is illustrated b... | I finally got around to dig a little.
Unfortunately I could not find tool, I did find resources though.
If all you want is mangle names in the gcc3 fashion, then know that gcc3 use the Itanium C++ ABI, which has a standardized name mangling scheme. I found two documents:
The Itanium C++ ABI page
A Calling Convention P... |
4,667,293 | 4,667,413 | How to implement decorators in C and C++ | I have a situation in C as well as in C++ which can be best solved with something like the Python like decorators: I have few a functions which I'd like to wrap around with something else so that before the function enters some statements are performs and when it leaves some other functionality is executed.
For instanc... | Use RAII (resource acquisition is initialization) to define the lock on the mutex. This would allow you to forget about point #2, i.e., you don't need to keep track of return statement to release the lock.
class Lock {
public:
Lock () { // acquire the semaphore }
~Lock () { // release the semaphore }
}
Next cr... |
4,667,461 | 4,667,747 | Porting a Python program to C | I would like to port a program which is using urllib and json (Python 3) to C. My question is which libraries exist to replace urllib and json in C and which are the best (easier, documented, fast)? If there are not good libraries in C I also accept C++
Thank you all.
| For JSON, json.org has a list of implementations for a variety of languages, including C. Most of them should be fairly lightweight and fast.
To replace urllib, you probably want to look at libcURL.
|
4,667,499 | 4,667,587 | Should "operator !=" always be implemented via "operator ==" in C++? | I currently review an old C++ codebase and see a lot of code going like this:
bool SomeClass::operator==( const SomeClass& other ) const
{
return member1 == other.member1 && member2 == other.member2;
}
bool SomeClass::operator!=( const SomeClass& other ) const
{
return member1 != other.member1 || member2 != othe... | In most cases the semantics of a!=b should be equal to !(a==b).
The same is true for about all the other operators: a<b should be equal to !(a=>b) and to !(a==b || a>b) and to a<=b && !(a==b) and so on and so forth.
To this purpose boost.operators offers some awesome tools to automatically generate operators in functio... |
4,667,792 | 4,667,898 | by-value return in functions of c++ | is this code correct in c++?
list<int> makelist(int litem)
{
list<int> newList;
newList.push_front(litem);
return newList;
}
should it make problems to return a list (of #include <list>) by value?
| As commented, returning by values will normally be optimized away (when running with optimization turned on). So if speed is the concern (which it shouldn't until it has been proven by a profiler) you shouldn't worry. If list on the other hand has some strange side effects when copying you should be aware of the number... |
4,667,834 | 4,668,426 | Does template class specialization/explicit instantiation improves compilation/linker speed? | Suppose the following template class is heavily used in a project with mostly int as typename and linker speed is noticeably slower since the introduction of this class.
template <typename T>
class MyClass
{
void Print()
{
std::cout << m_tValue << std::endl;;
}
T m_tValue;
}
Will defining a class specialization be... | in C++0x you will be able to use extern templates so that instantiation of templates happens only once just like extern variables.
This should help in compile times since the compiler would not have to instantiate the template with its arguments every time it sees it.
I haven't yet figured out exactly how I will be usi... |
4,667,890 | 4,670,668 | How to prevent buffer overflow in C/C++? | I am using the following code to redirect stdout to a pipe, then read all the data from the pipe to a buffer. I have 2 problems:
first problem: when i send a string (after redirection) bigger then the pipe's BUFF_SIZE, the program stops responding (deadlock or something).
second problem: when i try to read from a pipe ... | Your problem is that you are using blocking I/O calls, while both ends of the pipe are connected to the same process. If you don't know how much data there will be, this is just a deadlock situation waiting to happen.
printf is a blocking call, which means that it will not return until all data has been written to the ... |
4,667,946 | 4,667,975 | Using an STL List of a Struct in C++ | I know I'm probably doing something unforgivably stupid here, but for some reason my code won't compile and I'm not sure why.
#include <iostream>
#include <list>
//A queue for the working set
//x,y co-ords of the square, path length so far
struct square {
int x;
int y;
int path_length;
} square;
list<square>... | The list class is defined in the std namespace, so you have to either do this:
std::list<square> workingset;
Or this
using namespace std;
list<square> workingset;
|
4,667,974 | 4,668,150 | Implicit conversion between RWCString and const char * | RWCString str = "Y";
str.append("ES");
if("YES" == str)
cout << "YES == str" << endl;
if(str == "YES")
cout << "str == YES" << endl;
How does the implicit conversion take place in both cases? Which one is safe to use?
RWCString is a string class which has a constructor taking const char* and an conversion ope... | It is extremely likely that == is overloaded for comparisons between const char* and RWCString.
Otherwise either str is converted to const char * or the calls are ambiguous:
str == "YES" is ambiguous if there is an external or member operator== comparing two RWCStrings.
"YES" == str is ambiguous if there is an external... |
4,668,193 | 4,668,400 | What goes into main function? | I am looking for a best practice tip of what goes into the main function of a program using c++. Currently I think two approaches are possible. (Although the "margins" of those approaches can be arbitrarily close to each other)
1: Write a "Master"-class that receives the parameters passed to the main function and handl... | Why would you have one master class? What is its single area of responsibility?
"Master" or "application" classes tend to become big blobs that do way too many different things. Ultimately, what's the point? What did it buy you?
Why not use the main function to provide this main functionality? Define the high-level app... |
4,668,267 | 4,668,332 | C++, Ifstream opens local file but not file on HTTP Server | I am using ifstream to open a file and then read from it.
My program works fine when i give location of the local file
on my system.
for eg
/root/Desktop/abc.xxx works fine
But once the location is on the http server the file fails to
open.
for eg
http://192.168.0.10/abc.xxx fails to open.
Is there any alternate fo... | There are no utilities in the standard C++ library for accessing data via http protocol.
There are 3rd-party libraries though:
Libwww
libcurl
Another option is to have a virtual filesystem that maps remote http files as local files. This way you don't have to modify your application to access http. Something like http... |
4,668,306 | 4,668,719 | boost::asio::io_service throws exception | Okay, I seriously cannot figure this out.
I have a DLL project in MSVC that is attempting to use Asio (from Boost 1.45.0), but whenever I create my io_service, an exception is thrown. Here is what I am doing for testing purposes:
void run()
{
boost::this_thread::sleep(boost::posix_time::seconds(5));
try
{
... | Microsoft recommends not to call WSAStartup from DllMain, so your best bet would be to create an IO thread elsewhere.
The WSAStartup function typically leads to protocol-specific helper DLLs being loaded. As a result, the WSAStartup function should not be called from the DllMain function in a application DLL.
|
4,668,566 | 4,668,602 | Application has failed to start because MSVCP100D.dll was not found, reinstalling app may work | I googled on this and realized there are probably several causes to this so I will describe my scenario.
This happens when my application tries to load a .dll file built in another version of Visual Studio (2010), if I build the same project on Visual Studio 2008 the DLL file loads just fine...
I don't know if it matte... | If you link dynamically to the MSVC runtime then you need to install that runtime on every machine that will run your app.
Note that in this case you appear to be linking to the debug version of the runtime, it is not normal to distribute apps linked against the debug version of the runtime.
|
4,668,592 | 4,668,735 | IPC via mmap'ed file: should atomics and/or volatile be used? | I use a mmap'ed file to share data between processes.
The code is like this:
struct Shared
{
int Data;
};
int file = open("file.dat", O_RDWR);
Shared* shared = static_cast<Shared*>(
mmap(0, sizeof(Shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, file, 0));
shared->Data++;
The questions are:
Should I u... | You should not use volatile when changing an integer from more than one thread. Volatile is both not necessary and not sufficient. Atomic operations will do.
|
4,668,661 | 4,668,730 | Again and again... Pointer to member-function | Suppose:
class Parser
{
public:
void parser1(int a, int b, int c);
void parser2(int d, int e, int f);
void setupPtr();
void (Parser::*ptrParser) (int param1, int param2, int param3);
}
Parser::setupPtr()
{
if(bla bla)
{
ptrParser = &Parser::parser1;
}
else
{
ptrParser = &Parser:... | Given that you change the ptrParser field to be public, you need to write main this way:
int main()
{
Parser parser;
parser.setupPtr();
(parser .* (parser.ptrParser))(1, 2, 3);
return 0;
}
Let's try to understand the line.
First, to call a pointer-to-member-function of type void (Parser::*)(int, int, int),... |
4,668,674 | 4,668,753 | How to export Firefox bookmarks? | I am creating a simple c++ application for bookmark manipulation.
So I need to export bookmark from firefox and read it with c++ but seems that the bookmarks are stored in a folder always different ( for example on my pc this folder is: /larry/AppData/Roaming/Mozilla/Firefox/Profiles/bah0ikoo.default/ )
It should work ... | The file profiles.ini in %HOMEPATH%\Appdata\Roaming\mozilla\Firefox tell you the path of the distinct profiles that you can start Firefox with.
On Unix systems: ~/.mozilla/firefox/profiles.ini
|
4,668,760 | 26,843,934 | Converting an int to std::string | What is the shortest way, preferably inline-able, to convert an int to a string? Answers using stl and boost will be welcomed.
| You can use std::to_string in C++11
int i = 3;
std::string str = std::to_string(i);
|
4,669,004 | 4,669,034 | HTTP queries in C++ for Mac | I am porting a Windows C++ program that uses winhttp.h for HTTP POST and GET.
Please give suggestions on what I can use in C++ for Mac instead of winhttp.h.
Thanks
| Are you using Cocoa? You can use [NSUrlConnection class][1].
Otherwise, you can use a portable HTTP client in C or C++ such as CURL/LIBCURL.
[1]: http://mywebsite.com/page.php?order=Bananas DESC
|
4,669,041 | 4,669,130 | BMP image generated But displayed inverted | I have generated bitmap.dll through winddk.
Added manually as a printer driver selecting print-to-file driver.
Using this I create an image of my document using print command from file.
I am able to create image and view it, But the problem is that I get inverted(mirror) image.
cScans = pOemPDEV->bmInfoHeader.biHeight;... | Device Independent Bitmaps are documented as being laid out in memory with the bottom line at the start of the buffer. Its an experiment in cartesian co-ordinates perpetrated by the designers of OS/2 who were working with Microsoft at the same time Windows 3 was being developed.
There are two possible fixes:
Generate ... |
4,669,050 | 4,669,147 | When does boost::bind cast arguments to the required type? | When I use boost::bind to bind parameters to a function - when are they casted to the type required by the function (if an implicit cast is possible)?
How are they stored in the bind_t object? As the type originally passed to bind or as the type required by the function signature?
Specifically:
If I have a function of ... | This won't even work as there is no implicit conversion or implicit constructor to shared_ptr from SomeType*.
You should call
boost::bind(&SomeFun, boost::shared_ptr<SomeType>(somePtr))
if somePtr is a pointer you have just allocated with "new" and expect to be deleted later when the last reference of the shared_ptr g... |
4,669,273 | 4,669,297 | Nested inheritance in C++ | I've got question about nested inheritance in C++. I have three classes: Base, Middle and Top. Normally I use public inheritance when deriving from Middle, but I have one class (Top) which have inherit privately from Middle, however it should expose Base methods for public usage...
Here's my solution, is it ok?
class B... | Suppose Base has a member function foo, you can put this in Top:
public:
using foo;
The same for any other members you need to expose publicly.
|
4,669,283 | 4,670,383 | I am new to RUBY and i need to understand 3 functions | I have been given the 3 functions below. Can anybody please help me to understand these? I am trying to port an application to C++ using Qt, but I don't understand these functions. So please help me!
Thanks in advance.
function 1:
def read_key
puts "read pemkey: \"#{@pkey}\"" if @verbose
File.open(@pkey, 'rb') ... | There are probably two things about the above code that are confusing you, which if clarified, will help understand it.
First, @verbose and @key are instance variables, what a C++ programmer might call "member variables." The "if @verbose" following the puts statement literally means only do the puts if @verbose is tru... |
4,669,306 | 4,669,484 | Using cryptographic streams in C++ | I'd like to use some cryptographic operations (mainly integrty check hashsums). However I have problems with finding documentations of doing operations of such form:
bool read(std::istream &in) {
hasher hv(in);
// Do some operations on hv as if it was std::istream
hash_type h = hv.finish ();
hash_type h... | Implement your own istream using crypto++.
|
4,669,311 | 4,671,117 | Converting c++ string to int | I have the following data in a c++ string
John Doe 01.01.1970
I need to extract the date and time from it into int variables. I tried it like this:
int last_space = text_string.find_last_of(' ');
int day = int(text_string.substr(last_space + 1, 2));
But I got invalid cast from type ‘std::basic_string’ to type ‘int’. ... | Use streams to decode integers from a string:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string x = "John Doe 02.01.1970";
std::string fname;
std::string lname;
int day;
int month;
int year;... |
4,669,406 | 4,672,668 | IDE: C++ syntax errors on std::tr1 | Say I have something like:
#include <vector>
#include <algorithm>
#include <tr1/functional>
void bar(int value) {
// do something with value
}
void foo() {
// v is a std::vector<int>
std::for_each(v.begin(), v.end(),
std::tr1::bind(&bar, std::tr1::placeholders::_1)); // netbeans marks bind and placeho... | I'm prone to think that Netbeans' parser isn't able to correctly parse some stuff in std::tr1.
std::tr1 is not part of C++03, but will most likely be part of C++0x; for this reason many STL implementation use other C++0x features to implement it, for example the std::tr1::bind supplied by GCC 4.5.2 is implemented as a ... |
4,669,475 | 4,669,676 | data structure to keep track of "consumptions" | hey everyone,
i am writing a small application for my c++ class mini-project.
it's about managing clients, lines and services at a telecom company.
i am supposed to use a Consumption class wich is supposed to represent a monthly consumption of a service/line.
class Consumption
{
private:
Ligne* m_line;//the ... | Best structure for storing something in array-like style with keeping the constant acces time to any element is vector. It;s just like you got dynamic sized array.
Second option to go is deque. If you plan having very much data go with this one as it have better storage managment and you can edit it from both front an... |
4,669,524 | 4,669,664 | Is a using-declaration supposed to hide an inherited virtual function? | struct level0
{
virtual void foo() = 0;
};
struct level1 : level0
{
virtual void foo() { cout <<" level1 " << endl; }
};
struct level2 : level1
{
virtual void foo() { cout <<" level2 " << endl; }
};
struct level3 : level2
{
using level1::foo;
};
int main()
{
level1* l1 = new level3;
l1->foo();
level3... | An example in Standard section 10.3p2 makes it clear that using declarations do not override virtual functions.
This is a known g++ bug.
As you noticed, when calling the member function via a reference or pointer, rather than a case in which the dynamic type is known, the bug does not happen.
|
4,669,870 | 4,669,953 | What's wrong with const? | What are the known shortfalls of const in C++ and C++0x?
| The two main issues that I have seen frequent complaints about in newsgroups, are
The need to waste a lot of time on supporting non-const-aware APIs (especially Microsoft's).
The need to define both const and non-const version of a method.
I think the latter could/should be supported by the language.
Possibly in conj... |
4,669,877 | 4,669,961 | Specializing function template for both std::string and char* | As the title says I want to specialize a function template for both string and char pointer, so far I did this but I can not figure out passing the string parameters by reference.
#include <iostream>
#include <string.h>
template<typename T> void xxx(T param)
{
std::cout << "General : "<< sizeof(T) << std::endl;
}
tem... | Doesn’t the following work?
template<>
void xxx<std::string>(std::string& param)
{
std::cout << "String : "<< param.size()<< std::endl;
}
And the same for const std::string?
That said, don’t specialize a function template if you have the choice (and you usually do!). Instead, just overload the function:
void xxx(... |
4,669,881 | 4,669,934 | Unused Entity Issue "Expression result unused" XCode 4 (Clang LLVM) | The following C/C++ code results in an Unused Entity Issue with XCode 4 (Clang LLVM).
void stringMethod(const char *string){
while(*string!=0){
*string++;
//...
}
}
Its on that line: *string++; so it seems like clang didnt realize that the pointer address is increased?
I don't get, how to adjust this code.... | Try to remove the dereferencing operator *, you don't need to dereference the pointer when you increase it.
|
4,669,966 | 4,673,773 | Abstract class and operator!= in c++ | I have problem implementing the operator!= in a set class deriving from an abstact one. The code looks like this:
class Abstract
{
public:
//to make the syntax easier let's use a raw pointer
virtual bool operator!=(const Abstract* other) = 0;
};
class Implementation
{
SomeObject impl_; //that already i... | You don't want to implement equality operators, == or !=, in a base class. The base class has no idea how many or the content of the descendants.
For example, using the Shape class example:
struct Shape
{
virtual bool equal_to(const Shape& s) const = 0; // Makes Shape an abstract base class.
bool operator==(const... |
4,669,995 | 4,670,200 | What does boost::condition_variable::timed_wait() return on spurious wakeups? | The boost documentation says:
Returns:
false if the call is returning because the time specified by abs_time was reached, true otherwise.
But what is returned if there is a spurious wakeup?
| If the condition variable could figure that it is a spurious wake-up there would be no need to return, would it?
You need to check if the data protected by the mutex and the condition variable has changed to detect a spurious wake-up. The condition variable can not do that for you.
|
4,670,137 | 4,670,930 | prolonging the lifetime of temporaries | What is the design rationale behind allowing this
const Foo& a = function_returning_Foo_by_value();
but not this
Foo& a = function_returning_Foo_by_value();
?
What could possible go wrong in the second line (which would not already go wrong in the first line)?
| I'll answer your question... the other way around.
Why did they allowed Foo const& foo = fooByValue(); to begin with ?
It makes life (somewhat) easier, but introduces potential undefined behavior all over the place.
Foo const& fooByReference()
{
return fooByValue(); // error: returning a reference to a temporary
}
T... |
4,670,239 | 4,671,453 | SQL Query notification from C++ ADO | I have two apps that need to receive notifications when data in a table changes. One .NET and the other C++ MFC. I decided to go with SQL Query Notifications.
I have built a proof of concept for the .NET app with SqlDependency class, but am struggling with the MFC version.
I found this http://msdn.microsoft.com/en-us... | I can't see example code for C++ anywhere.
Rather than write and debug this (complex) event detection code twice, it would be possible (and preferable imo) to implement it in C#, and then expose the required function to your MFC app via COM interop. See here for a brief overview.
|
4,670,307 | 4,670,446 | Using boost bind to access member function of inner class | I'm trying to access a member function of a nested class in a find_if expression.
My code below causes a compile error in the bind expression - (‘COuter::innerClass’ is not a class or namespace).
Could you help me with the correct bind expression?
vector<COuter> vec;
vec.push_back(COuter());
vector<COuter>::const_ite... | Correct expression is bind(&CInner::GetTemp, bind(&COuter::innerClass, _1)).
|
4,670,754 | 4,670,793 | C++: How to make comparison function for char arrays? | Is this possible? i get weird error message when i put char as the type:
inline bool operator==(const char *str1, const char *str2){
// ...
}
Error message: error C2803: 'operator ==' must have at least one formal parameter of class type ... which i dont understand at all.
I was thinking if i could directly compar... | It is not possible. As your compiler points out, you cannot overload this operator for primitive data types. At least one side of the comparison must be non-primitive for the overload to be possible.
In the same sense, you cannot derive a new class from a primitive data type (to add functionality to it).
|
4,670,782 | 4,670,836 | The difference between delete and delete[] in C++ |
Possible Duplicate:
delete vs delete[] operators in C++
I've written a class that contains two pointers, one is char* color_ and one in vertexesset* vertex_ where vertexesset is a class I created. In the destractor I've written at start
delete [] color_;
delete [] vertex_;
When It came to the destructor it gave me ... | You delete [] when you newed an array type, and delete when you didn't. Examples:
typedef int int_array[10];
int* a = new int;
int* b = new int[10];
int* c = new int_array;
delete a;
delete[] b;
delete[] c; // this is a must! even if the new-line didn't use [].
|
4,671,328 | 4,671,482 | dlopen and global variables in C/C++ | Due to some restrictions I am being forced to load a library written in C at runtime. A third party provides two library to me as static archives which we turn into shared objects. The application I'm working with loads one of the libraries at runtime based on some hardware parameters. Unfortunately one of the libra... | Yes, you can use dlsym to access globals (as long as they are exported, and not static). The example below is in C++ and Mac, but obviously C will work fine.
lib.cpp:
extern "C" {
int barleyCorn = 12;
}
uselib.cpp
#include <dlfcn.h>
#include <iostream>
using namespace std;
main()
{
void * f = dlopen ("lib.dylib",... |
4,671,517 | 4,671,543 | C++ Double Dispatch problems | This is part 2 to a problem I previously asked: Is it possible to have polymorphic member overloading in C++?
Using the Wiki example I created this example.
http://en.wikipedia.org/wiki/Double_dispatch
My problem is that the compiled code never looks up the vtable, and always uses the base instead of the inherited clas... | You only did single dispatch, not double dispatch. The idea is that in xVehicle, taking an xMapObject&, you would call ref.bump(*this); which is double dispatch.
|
4,671,629 | 4,671,698 | How to use basic_istream when you have a std::string | I have a function that uses basic_istream as an argument, and I have a std::string with the data I need to pass it. How do I do that?
| You can put the string data into a stream:
std::string x;
std::stringstream ss(x); // put string into stream
function_taking_stream(ss);
|
4,671,827 | 4,671,851 | _begintheadex function call problem | I have a class SoundManager which contains a function called 'recordLoop'. In the constructor of the SoundManager, I am using this code:
recordHandle = (HANDLE)_beginthreadex(NULL,0,recordLoop,
(void*)exinfo->length,CREATE_SUSPENDED,0);
It is giving me the following errors:
error C3867: 'SoundManager::r... | It's illegal to start a thread on a non-static class member since there is no way for the created thread to know what this is.
What is the definition of recordLoop?
|
4,671,900 | 4,672,008 | How do I use the MinGW gdb debugger to debug a C++ program in Windows? | I have looked for documentation on this and found nothing. I have MinGW installed and it works great. I just don't know how to use the debugger.
Given some simple code, say in a file called "mycode.cpp":
int main()
{
int temp = 0;
for (int i = 0; i < 5; ++i)
temp += i;
return 0;
}
...how would I ... | The first step is to compile your program with -g to include debugging information within the executable:
g++ -g -o myprog.exe mycode.cpp
Then the program can be loaded into gdb:
gdb myprog.exe
A few commands to get you started:
break main will cause the debugger to break when main is called. You can also break on l... |
4,672,091 | 4,672,204 | Use of 64-bit types? | I am writing some hash functions for a compiler and I use the __int64 datatype frequently. The compiler is intended to be supported (and so far is) on different OS's. I know that __int64 is a type that can be compiled by most major C++ compilers for my target systems so that's not the problem. I am using hash functions... | 64bit sized integers aren't substantially slower at all on a 32bit x86 architecture. They're not as fast as 32bit ints, obviously, but aren't notably slower. It's not at all reckless to use a 64bit int for hashes regardless of x86 or x64. The additional overhead will likely be minimal compared to say, a couple of unnee... |
4,672,152 | 4,673,320 | Call of overloaded function is ambiguous | What does this error message mean?
error: call of overloaded ‘setval(int)’ is ambiguous
huge.cpp:18: note: candidates are: void huge::setval(unsigned int)
huge.cpp:28: note: void huge::setval(const char*)
My code looks like this:
#include <iostream>
#define BYTES 8
using namespace std ;
class huge {
p... | The literal 0 has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.
As your setval function can accept either an int or a char*, the compiler can not decide which overload you meant.
The easiest solution is to just cast the 0 to the right type.
An... |
4,672,382 | 4,672,406 | Calling non-DLL function from DLL function | I am writting a DLL:
#include "stdafx.h"
_DLLAPI int __stdcall myDLLFunc()
{
return test(4);
}
int test(int arg)
{
return arg * arg;
}
But when I try to compile it in MS VC++ Express it says:
error C3861: 'test': identifier not found
How do I call test from myDLLFunc?
Am I missing the obvious?
Thanks in... | Put the called function ahead of the caller in your code and it should compile. C++ does not do 'look ahead' for called functions, they must be declared ahead of any usage.
#include "stdafx.h"
int test(int arg)
{
return arg * arg;
}_DLLAPI int __stdcall myDLLFunc()
{
return test(4);
}
Typically, you wou... |
4,672,438 | 4,672,888 | How to access protected method in base class from derived class? | Here is a sample of code that annoys me:
class Base {
protected:
virtual void foo() = 0;
};
class Derived : public Base {
private:
Base *b; /* Initialized by constructor, not shown here
Intended to store a pointer on an instance of any derived class of Base */
protected:
virtual void... | Protected members in a base-class are only accessible by the current object.
Thus, you are allowed to call this->foo(), but you are not allowed to call this->b->foo(). This is independent of whether Derived provides an implementation for foo or not.
The reason behind this restriction is that it would otherwise be very ... |
4,672,522 | 4,674,079 | Sortable QHBoxLayout | I'm using Qt to create a sortable bar graph-like widget. The widget is laid out with a QHBoxLayout for each bar in the graph (which are also widgets).
When the user changes the sorting parameters, my controller clears the layout, sorts it, and calls addWidget on every item in order. The problem I'm facing is that thi... | From documenation of void QLayout::setEnabled(bool enable)
Enables this layout if enable is true, otherwise disables it.
An enabled layout adjusts dynamically to changes; a disabled layout acts as if it did
not exist.
By default all layouts are enabled.
|
4,672,572 | 4,672,651 | How can I configure windows to generate a core dump from an application? | How can I configure windows to generate a core dump from an application?
I'm using Win xp, and the application is build with Visual Studio 2003.
| Microsoft has a free tool called Userdump.exe which will do this.
It's pretty simple to use that tool to create a dump (.dmp) file for a process that shuts down with an exception or to create a dump file for a hanging process
|
4,672,783 | 4,672,866 | object in a set iterator | I can get a method of a class in a set iterator ?
#include <iostream>
#include <string>
#include <set>
class student{
public:
student(std::string n){
name=n;
}
void print(){
std::cout << name << std::endl;
}
bool operator < (const student & s1){ return true;}
bool oper... | You need to add a const qualifer to your print member function:
void print() const
{
std::cout << name << std::endl;
}
Objects in an std::set are necessarily const, since they are used as keys. When an object (or reference) is constant, you can only call member functions of that object which are declared with the c... |
4,672,811 | 4,672,833 | Private and Protected Members | I'm having trouble understanding the difference between private and protected members in a C++ class. In simple terms, what is the difference?
| protected members are accessible by derived classes. private members are not.
Generally (most of the time) members should either be private or public. It is rare and unusual to need a protected member (edit) in a well-designed system.
EDIT:
Maybe I should elaborate on why protected members can be a code-smell.
If der... |
4,672,840 | 4,672,938 | how to use eof in a for loop with iterating integer c++ | this gives me a segmentation fault:
for (int i=0; !file.eof();i++)
{
getline(file,line);
roughInput.lines[i].split(line);
}
and this doesn't
for (int i=0; i<2;i++)
{
getline(file,line);
roughInput.lines[i].split(line);
}
from my understanding for should increase i by one until the end of file, right?
since i ... | Your loop is probably running one time too many. file.eof() will not return false until after you have tried to read while you are at the end of the file. You probably want to put the check in between the getline call and the split:
getline(file, line);
if (!file.eof())
roughInput.lines[i].split(line)... |
4,672,858 | 4,672,934 | Symbolic vs word operators eg ( '||' vs 'or' and '!' vs 'not') | I think or is keyword in c++.
It might be that I've been doing too much python code recently but I find or is more readable than || and xor much more readable than ^.
Is it a good idea to use the word alternatives to the symbolic operators?
Why don't I see them used more?
|
Is it a good idea to use the word alternatives to the symbolic operators?
Completely depends on the target audience for your code – both people and tools. People can be unused to them, and some tools don't recognize them. (Sometimes those tools use <ciso646> to define them as macros.)
I've started to use "and" and... |
4,672,985 | 4,744,244 | map return type of C++ function to byte[][] in Java | I have a c++ function declared as
unsigned char** classify
I am using the following interface file in SWIG
%module PWrap
%include "std_string.i"
%include "arrays_java.i"
%apply byte[][] {unsigned char**};
%{
#include "Classifier.h"
%}
%include "Classifier.h"
which generated some files, including a SWIGTYPE_p_p_unsi... | I'd better use use direct JNI instead of SWIG to have full control over such data types.
Anyway returning char ** is not effective because array pinning can't be used. Probably that's why your SWIG wrapper does not do what you want - your classify should accept char ** as a parameter and not return it. I don't know SWI... |
4,672,991 | 4,673,042 | Proper casting for fstream read and write member functions | Although there was a lot of lines written on the topic of reinterpret_cast, and how bad it is, I'm still puzzled with best way to avoid it, especially when dealing with functions like read and write from fstream. So, here is my dilemma...
Let's say we have an integer array that we want to fill with some data from a fil... | Why don't you declare a as char* instead, like this:
//int *a = new int[100];
char *a = new char[100];
iFile.read(a, 100 );
No casting required now.
EDIT:
Okay, I read your comment and the commented line in your post. In that case:
iFile.read(reinterpret_cast<char*>(a), sizeof(int)*100);
should suffice.
However,I ... |
4,672,998 | 4,673,069 | c++: using type safety to distinguish types oftwo int arguments | I have various functions with two int arguments (I write both the functions and the calling code myself). I am afraid to confuse the order of argument in some calls.
How can I use type safety to have compiler warn me or error me if I call a function with wrong sequence of arguments (all arguments are int) ?
I tried ... | You will have to create wrapper classes. Lets say you have two different units (say, seconds and minutes), both of which are represented as ints. You would need something like the following to be completely typesafe:
class Minute
{
public:
explicit Minute(int m) : myMinute(m) {}
operator int () const { return... |
4,673,068 | 4,673,124 | Question about delete() a class instance and its static methods/variables | Consider this class for demonstration purposes:
class test{
private:
int y;
HANDLE handle;
static int x;
public:
test()
int add();
static int sub();
}
test::test() {
[....]
sub = 1;
handle = (HANDLE)_beginthreadex(NULL,0,&test::sub,NULL,0,0);
}
test::sub() {
[....]
_endthreadex... | Static variables have program lifetime. They are created when the program starts, and destroyed when the program ends. Only one exists, and it's not in the individual objects.
|
4,673,110 | 4,673,278 | Trying to understand RapidXml memory allocation | I'm using RapidXml in a c++ program. Well ok no problem it works. I just do not understand why I must use pointers instead of variable values...
If you take a look to the RapidXml wiki page, some examples are provided, this is the one provided by RapidXml developers:
#include <iostream>
#include <string>
#include "rapi... | Returning a pointer is probably done to avoid calling the copy constructor of the node. It is faster to just return a pointer, especially considering the node is probably already allocated somewhere internally.
They could have also returned a reference, but they might wish to retain the ability to return NULL on inval... |
4,673,419 | 4,673,445 | how to send SMS to a mobile phone using software program (like yahoo messenger)? | I am trying to write a small program using Qt to send SMS messages to a mobile phone. Something like what Yahoo Messenger provides. You can send SMS messages to mobile phones if mobile service provider is supported. I would like to know what happens behind the scenes after you click "Send". Especially how does the mess... | Yahoo would've purchased access to (or run their own) SMS gateway. The exact method of transferring the message from Yahoo->Gateway would depend on the gateway's API. Could be XML, could be a proprietary binary format, could be a simple HTTP POST, etc... The SMS gateway would take care of the details of getting the mes... |
4,673,556 | 4,673,598 | is there a library can work with input file that contains descriptions and values? | i'm looking for a library that can do the following :
ask questions and generate an input file
read that input file
while reading the modified input file, the lib assigns the value into the program accordingly to the description in the input file.
i wrote a simple program that does it, like this:
>./main
gaussian wid... | What you are looking for is program options from boost. However you may need to adapt your input file.
|
4,673,564 | 4,673,933 | What is the best way to process the content of sysfs using C/C++? | The Linux kernel exposes information about the current environment using the sysfs filesystem in /sys. I'm interested in getting information about online CPUs and their memory hierarchy (Level 1 to Level 3 caches).
Since all this information is basically text files I could write a parser on my own, but I'm curious wha... | The kernel authors have published sysfs-rules.txt, which explains how sysfs must be used. They point out in particular
Do not use libsysfs
|
4,673,569 | 4,673,814 | Why SWIG needs to generate manifest file with mt.exe? | I'm testing swig, and I found that SWIG's vcxproj file runs the mt.exe to generate the manifest file.
swig -c++ -csharp example.i
CL.exe ... -> compile the c++ source
link.exe ... -> generate dll
mt.exe ...
Csc.exe ...
What is this for? I skipped the mt.exe, but it seems to work fine.
| It was a Very Big Deal in versions of VS prior to 2010. mt.exe embeds the auto-generated manifest in the executable image, important to get the DLL dependencies that are stored in the Windows side-by-side cache listed. Not much of a big deal anymore, it only embeds an "I'm compatible with Vista" manifest now. The si... |
4,673,584 | 4,673,689 | BASH scripts for generating inputs to parallel C++ jobs | I'm an amateur C++ programmer trying to learn about basic shell scripting. I have a complex C++ program that currently reads in different parameter values from Parameters.h and then executes one or more simulations with each parameter value sequentially. These simulations take a long time to run. Since I have a cluster... | Say you want to run the program simulate with inputs foo, bar, baz and quux in parallel, then the simplest way is:
inputs="foo bar baz quux"
# Launch processes in the background with &
children=""
for x in $inputs; do
simulate "$x" > "$x.output" &
$children = "$children $!"
done
# Wait for each to finish
for ... |
4,673,720 | 4,673,857 | Private inheritance using directive, overloads? | I'm using private inheritance in a project, in the "implemented in terms of"-sense. The base class defines operator[], and this is the functionality I want to use. Thus, I have
class A : private B {
using B::operator[];
// ...
};
However, how can I control which version of the operator[] I get? In fact, I need... | My understanding is that your using should automatically bring in all the different overloads of the operator. Are there certain overloads you want to exclude from being brought into the child class? In that case it might be better to split the work into several differently named functions in the parent and only using ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.