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 |
|---|---|---|---|---|
6,642,777 | 6,642,948 | does it make sense to inherit privately from an abstract (pure virtual) class? | suppose this construct
struct InterfaceForFoo
{
virtual void GetItDone() = 0;
};
class APoliticallyCorrectImplementationOfFooRelatedThings : private InterfaceForFoo
{
public:
void GetItDone() { /*do the thing already*/ };
};
Now, i'm wondering if inheriting privately from an interface in this way do ha... | Huh, everyone here says "no". I say "yes, it does make sense."
class VirtualBase {
public:
virtual void vmethod() = 0;
// If "global" is an instance of Concrete, then you can still access
// VirtualBase's public members, even though they're private members for Concrete
static VirtualBase *global;
};
/... |
6,642,801 | 6,650,920 | QT Quick or C++ Checking for valid email input (email format validator) | Please I am trying to write a code that checks whether a users input is a valid input or not in QT quick.
I want it to check and if it does not fulfill the usual email format not allow user to submit but notify him that the email is wrong.
I have seen samples for php and some c++ but from my experience, I cannot really... | Use this EMail validation javascript code
function validateForm(email)
{
var atpos=email.indexOf("@");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
//Not a valid e-mail address
return false;
}
}
Read this to see how you can import javascript into QML... |
6,642,865 | 6,642,898 | getline not asking for input? | This is probably a very simple problem but forgive me as I am new.
Here is my code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string name;
int i;
string mystr;
float price = 0;
cout << "Hello World!" << endl;
cout << "What is your name? ";
cin >>... | You have to be careful when mixing operator>> with getline. The problem is, when you use operator>>, the user enters their data, then presses the enter key, which puts a newline character into the input buffer. Since operator>> is whitespace delimited, the newline character is not put into the variable, and it stays ... |
6,642,945 | 6,646,299 | Enumerating Privileges (Local Security Policy) | I am aware that NT header has all constants defined like SE_TAKE_OWNERSHIP_NAME, and so there are functions available to convert these into human readable form (Take ownership of files or other objects).
My question is how to enumerate these names? With different versions of Windows, not all SE-names would be applicabl... | Use LsaEnumeratePrivileges (defined in ntlsa.h, which is in the WDK - inc/api):
NTSTATUS
NTAPI
LsaEnumeratePrivileges(
__in LSA_HANDLE PolicyHandle,
__inout PLSA_ENUMERATION_HANDLE EnumerationContext,
__out PVOID *Buffer,
__in ULONG PreferedMaximumLength,
__out PULONG CountReturned
);
The buffe... |
6,642,980 | 6,643,170 | Obfuscate External API Calls C++ | I have a code in C++ that calls functions from external library. The function I called is CreateProcess like below.
CreateProcess(NULL,pProcessName,NULL,NULL,false,CREATE_SUSPENDED,
NULL,NULL,&suStartUpInformation,&piProcessInformation)
Now when I compile the code and dissemble it, the assembly shows the plain t... | Any function that is imported by name will always have the name embedded into the binary (in the import descriptor thunk to be exact), the detailed parameter info is gotten from the pdbs as Steve mentioned (however analysing debuggers like ollydbg can deduce args, due to the symbol name being available). The only ways ... |
6,643,176 | 6,643,195 | QtWebKit dependency missing from qmake generated Makefile | I just started working with Qt (in C++), so I followed a "hello, world" example I found online. I created the program hello.cpp in the directory hello:
#include <QtGui>
int main(int argc, char *argv[]) {
QApplication app (argc, argv);
QLabel label ("Hello, world!");
label.show();
return app.exec();
}
... | You need to add:
QT += webkit
to your .pro file, and re-run qmake.
qmake -project does not try to guess what modules you need in your code.
If you have more than one module, the usual syntax is like:
QT += webkit xml network
|
6,643,516 | 6,643,682 | Windows message queue handling within DLLs | I have a dll that is loaded by an application, I can not modify the source of the application (as I do not have the source) and I want to register a system wide hotkey with the plugin. I can register the hotkey via something like RegisterHotKey(NULL, 1, MOD_CONTROL | MOD_NOREPEAT, 0x42) (see here) but I'm not sure how ... | Here's how it should be done:
your DLL creates a thread
this thread runs the message loop (GetMessage()/DispatchMessage()) -- that sort of thing. GetMessage() is what you really need, whereas DispatchMessage() is needed if you create a window (see below)
Now one of the two things should happen:
the thread creates a... |
6,643,518 | 6,643,678 | Visual C++ 2005: How to view the window during a debugging session | Is this possible? When I'm debugging a program I can't bring the window up to see any changes. It's minimized during the debugging while I step through the program and I'd like to see the program changes while I step.
The only way I might see it is in Windows 7 you can hover over the task-bar to get a look at the progr... | Two choices:
Don't maximize the IDE window and make it smaller until you can see the program window.
Have two monitors and put the program window on the secondary monitor.
|
6,643,528 | 6,643,539 | Passing a class as argument which has a private constructor that takes no parameters | Simulator is supposed to carry a copy of Missile object inside it. But Missile has no public constructor with zero parameters, so I'm not able to pass it as parameter.
I'm using Visual Studio 2010, and it gives the following errors:
Error 1 c:...\simulator.cpp Line #5
error C2248: 'Missile::Missile' :
cannot acces... | You would use what's called a ctor-initializer (some people call it an "initializer list", although the C++ standard actually calls it a "ctor-initializer"):
// In your Simulator.cpp file:
Simulator::Simulator(const Missile & missle) : m_Missile(missle)
/*^^^^^^^^^^^^^^^^*... |
6,643,550 | 6,643,642 | C++ coming from Java and Objective-C | So, I know both Java and Objective-C quite well, but (perhaps strangely) never really learned C++. Obviously, the languages are all related, but there are syntactical differences that I don't fully understand. Is there a nice document that describes the basics of C++, but still assumes the learner knows a programming l... | Even though the languages of this family are all related, that does not mean that you can casually move from one to the other and expect to write beautiful code. You have to learn the language's idioms and idiosyncrasies, and experience its strengths and way of thinking.
I would recommend reading Stroustrup's original ... |
6,643,615 | 6,643,669 | Is delegating calls between classes bad practice? | I know that delegating from one method to another in the same class is okay as it reduces code duplication, but is delegating calls to other class types considered bad practice?
For example:
Doing this is okay.
double Point::GetDistanceFrom(const Point& point) const {
return GetDistanceFrom(this->GetX(), this->Ge... |
is delegating calls to other class types considered bad practice?
The OO design rule that is probably most applicable is encapsulation. The Point class shouldn't really know that the ptSegDist method exists on Line. But it is free to do anything it wants with its public interface.
In this case, it seems like you co... |
6,643,645 | 6,643,662 | How do I step through a method in an unmanaged DLL when loaded from a managed project? (Visual C++/C#) | I have a Visual Studio 2010 solution with 3 projects. The first is an unmanaged DLL project (C++) that I've written with a few DLL exports. The second project is a Managed wrapper for the first project (C# using DLLImport). The final project is a WPF application I'm using to test out the functionality of the first proj... | Try enabling unmanaged code debugging:
To enable debugging of unmanaged code
With a project selected in Solution Explorer, on the Project menu, click
Properties.
Click the Debug tab.
Select the Enable unmanaged code debugging check box.
|
6,643,757 | 6,645,240 | How do I solve memory leaks that are reported to reside in STL string? | For a school project, we have to send big files across the network., we must use Poco::XML for our data.
After our files are send over the network, it appears that the memory does not free.
Here is an example for a file of ~9 Mb on the receiving part:
valgrind --leak-check=full --show-reachable=yes -v ourExecutable par... | I would make this a comment, but apparently I don't have the rep. Have you remembered to make the destructor for Command virtual? If name or data are fields of PutCommand rather than Command and the Command destructor is not virtual, they may not be freed properly when you delete command in handleClientPacket.
|
6,643,760 | 6,643,895 | remove elements of a vector from another vector | I have two vectors of XML DOM nodes:
vector<IXMLDOMNodePtr> A; //filled in somehow
vector<IXMLDOMNodePtr> B; //filled in somehow
B is a subset of A. I want to remove B from A and I also want to preserve the order of A, so that if an element in A is removed it is replaced with a blank element. It would look like this:
... | I doubt there is a perfect algorithm for you in the standard library. The amount of work depends on whether the two vectors are pre-sorted or not, or if you can sort them.
If you cannot sort your vectors, then you are left in O(n^2) territory, since for each element in B to be removed from A, you have to search A once... |
6,643,893 | 6,643,979 | Transparent C++ Number/Int Wrapper | I've made a class for working with bits for unsigned int(8, 16, 32...), and I've been trying to benchmark it compared to the bare bitwise operations but getting an accurate test of the speed of bitwise operations is complicated to say the least. The reason for the wrapper is that it is a lot less complicated to use.
No... | You can setup a custom class and overload all the relevant operators (arithmetic operators, comparison operators, bitwise operators, conversion operators) and supply your own behaviour as needed.
As far as I know, it would indeed be possible to make it behave like an int in almost all respects.
An inlining compiler wi... |
6,643,903 | 6,643,923 | Unresolved external symbol |
Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?
I'm relatively new to C++ (as you can probably tell by the question) and I've hit a problem. I have two files: Drives.h and Drives.cpp
Drives.h
#pragma once
enum MountMode
{
User,
System,
Both,
A... | As the error message says, you have not implemented the constructor and destructor of Drive:
Drive::Drive(void) {
...
}
Drive::~Drive(void) {
...
}
Creating a local variable of class type (as you do in Drive USB0;) will invoke that class' constructor, and the destructor will be invoked at the end of the varia... |
6,644,277 | 6,644,920 | Bool array problems in c++ | Is an array of bools also "optimized", like a vector<bool> is? I want to make arrays of true or false, but I also dont want the problems that some with vector<bool> to show up in an array, such as slow access times
| I think the C++ default implementation is mainly for saving the space, while the access time may be affected.
if you need quicker access time, you may have implement it by yourself and sacrifice the space.
|
6,644,313 | 6,644,350 | Detecting non-character press from WM_KEYDOWN message | Is there a function in win32 that can take the Virtual Key code for the CTRL, ALT or capslock key & return a string saying "CTRL", "ALT", "CAPSLOCK"?
I can only receive WM_KEYDOWN messages but not WM_CHAR messages. I know I can determine what character key has been pressed by passing the Virtual Key code to the functio... | You can pass in the lParam value from WM_KEYDOWN to GetKeyNameText and it will return the key name for you.
|
6,644,430 | 6,644,460 | Virtual Key Codes: Same across ALL PC's | On different Windows OS's & on versions of windows that are running different langauges(keyboards, encoding etc.) are the virtual key codes always the same?
So from looking at MSDN I can see that VK_RETURN = 0x0D. Will the Return key always have this value regardless of what version of windows or language or etc.?
MSDN... | Yes, this is the point of having virtual keys in the first place. There are a whole heckofalot of complications to turn a virtual key into a real key, WM_CHAR. That's keyboard layout nightmare. You don't have to fear VK_RETURN, that one is in the usual place.
|
6,644,465 | 6,644,485 | Able to instantiate an object but not access its functions - 'Symbol(s) not found' error | I'm using the 'TPCircularBuffer' class for creating a circular buffer object, from this website.
This is my current code:
TPCircularBufferRecord bufferRecord; //1
TPCircularBufferInit(&bufferRecord, kBufferLength); //2
Line 1 works fine, so that means the linker has found the .cpp and .h files f... | You're mixing and matching C and C++ code.
The TPCircularBuffer.h isn't C++ safe, so when you include it in your C++ source, it'll get treated as C++. That'll fail, in this case only at link time. The linker will look for C++ name mangeled symbols for the cicrular buffer functions, but TPCircularBuffer.c is compiled as... |
6,644,597 | 6,644,624 | How to make boost ptree parse xml and json the same way? | So lets take a look onto a littel bit modified example code:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
void load(const std::string &file_path)
{
using boost::property_tree::ptree;
... |
How to make boost property_tree produce same results on JSON as it parses XML?
Have Boost.PropertyTree output JSON. Then it will be able to input that JSON file.
Boost.PropertyTree is used for storing properties. It is a way to save properties in human-readable formats, and restore those properties later.
It is not a... |
6,644,603 | 6,644,629 | How can I get the connected host's IP address from a Windows Socket (C++)? | I've seen this asked before, but I never found an answer that worked. I need to get the explicit IP address (i.e. 123.456.789.100) and PORT number of the computer that my server is connected to in order to forward that info to other clients. I'm using WinSock2.h on Windows 7 (Home Premium), Visual Studio 2010 Professio... | getpeername() is the function you want to be using.
Some errors I see in your code:
1) You're allocating addr on the heap. No need to do that, just declare "sockaddr_in addr;" on the stack instead, and pass &addr (instead of addr) to your getpeername() call.
2) addrsize is being set to the size of a pointer (e.g. 4 or... |
6,644,625 | 6,644,660 | How to render lower resolution scene stretched to fullscreen native resolution? | I have seen this kind of functionality in DirectX apps only: when you resize the window, the rendering will also stretch accordingly, and it looks like it was actually a texture that was stretched.
How can i do this efficiently in OpenGL ? The purpose for this is to create a fullscreen application with native resolutio... | You will need to render to a texture or renderbuffer, then do a glBlitFramebuffer to the actual default framebuffer. Then swap buffers as normal.
|
6,644,807 | 6,644,817 | what does "##" symbol mean in C++ |
Possible Duplicates:
Macro expansion in C++
What is the purpose of the ## operator in C++, and what is it called?
What does "##" symbol mean in C++? I came across with it while I was reading someone's source code. More specifically, what does this statement mean:
if ( v > ## = 0.1 * threshold )
| In a #define macro, ## is a preprocessor token, which says to paste the surrounding two things together. So assuming you saw this within a #define, it is a very strange way of writing
if ( v >= 0.1 * threshold )
If you already subsituted either the > or =, it's not quite so strange. Just a somewhat strange trick.
|
6,645,093 | 6,645,412 | How to rotate a group of 2D shapes around an arbitrary point | and i'm making a 'Body' class which holds a bunch of 2D shapes together to form a single moveable, rotatable body.
What i need to know is how i can rotate each individual shape in a way that makes it look like the whole body is rotating, not each shape doing it's own rotation around it's center.
I can't just change ea... | The way to rotate by an arbitrary point is first substract the point coordinates, do the rotation about the origin and then add the point coordinates.
x2 = px + (x1-px)*cos(q)-(y1-py)*sin(q)
y2 = py + (x1-px)*sin(q)+(y1-py)*cos(q)
where px, py are the rotation point coordinates, and x1,y1 the original 2D shape vertex ... |
6,645,105 | 6,645,435 | Problem triing to compile basic Boost PropertyTree sample - compilation error. What to do? | So this is official Boost PropertyTree example, I try to compile it on my visual studio 2008 and same on VS2010 get Error C2228: left of '.put_value' must have class/struct/union c:\program files (x86)\boost-1.46.1\include\boost\property_tree\detail\ptree_implementation.hpp 795 1
Here is code I use:
#include <stdio.... | The sample code for 1.46.1 has changed:
http://www.boost.org/doc/libs/1_46_1/libs/property_tree/examples/debug_settings.cpp
The relevant change is
BOOST_FOREACH(const std::string &name, m_modules)
pt.add("debug.modules.module", name);
|
6,645,259 | 6,645,269 | Retrieving member item from a queue? | I'm new to c++ so please bear with me if my terminology and knowledge is off.
I'm trying to print out or retrieve the string jobName after passing the JOB to a queue. In queue.h I have:
struct JOB {
string jobName;
int runtime;
};
In queue.cpp I am trying to write the appropriate method:
void Queue::display(){
c... | The key will be in the definition of struct Queue::QueueNode. Look there, and see what field it has that will give you a struct JOB.
|
6,645,267 | 6,645,284 | Reversing a string, weird output c++ | Okay, so I'm trying to reverse a C style string in C++ , and I'm coming upon some weird output. Perhaps someone can shed some light?
Here is my code:
int main(){
char str[] = "string";
int strSize = sizeof(str)/sizeof(char);
char str2[strSize];
int n = strSize-1;
int i =0;
while (&str+... | A valid string should be terminated by a null character. So you need to keep the null character in its original position (at the end of the string) and only reverse the non-null characters. So you would have something like this:
str2[strSize - 1] = str[strSize - 1]; // Copy the null at the end of the string
int n = st... |
6,645,486 | 6,645,522 | ways to query template specializations at run-time / avoiding the big switch | I have a enum type:
enum class MyEnumType { A , B , C };
and i want to map these enums to description attributes; i like this approach a lot:
template <typename T>
struct MyEnumTypeDescription
{
inline const char* get() { static_assert("description not implemented for this type"); };
};
template<>
const char* MyEnum... | I would suggest to map it to an array:
enum MyEnumType { A , B , C };
const char *pEnumDescription[] = { "A", "B", "C" };
And based on index you can get the type at runtime.
const char* getDescriptionFromEnumerator(MyEnumType t)
{
return pEnumDescription[t]; // just one statement instead of switch/case
}
|
6,645,550 | 6,646,163 | How to save image using libcurl | I wanted to use libcurl for a project which involves getting an image from a webpage.
The URL looks like this:
http://xxx.xxx.xxx.xxx/cgi-bin/anonymous/image.jpg
Using command-line cURL I can retrieve the image using
$curl -o sampleimage.jpg http://xxx.xxx.xxx.xxx/cgi-bin/anonymous/image.jpg
I want to know the equival... | Use a full path in the open call so that you know where to look.
Also you should look at the perror function so you can print the reason why the open fails when it does - saves a few headaches.
Last thing: initialize fp to null, or only fclose(fp) if it was really open. As it stands, if curl_easy_init fails, you'll att... |
6,645,961 | 6,646,015 | How can I make my implementation of Project Euler 25 faster, so I can actually compute the answer? | Here is my implementation of Problem 25 - Project Euler (see comments in code for explanation of how it works):
#include <iostream> //Declare headers and use correct namespace
#include <math.h>
using namespace std;
//Variables for the equation F_n(newTerm) = F_n-1(prevTerm) + Fn_2(currentTerm)
unsigned long long newT... | There is a closed formula for the Fibonachi numbers (as well as for any linear recurrent sequence).
So F_n = C1 * a^n + C2 * b^n, where C1, C2, a and b are numbers that can be found from the initial conditions, i.e. for the Fib case from
F_n+2 = F_n+1 + F_n
F_1 = 1
F_2 = 1
I don't give their values on purpose here. It... |
6,646,416 | 6,646,494 | How to iterate an xml file and store it in map | How to iterate an file using rapidXml and store it in a map... Something like creating a dictionary using the contents of file. I have tried this but i can get only the first level of key-value pairs not the inner levels.
typedef map <string, string> MapType;
MapType mProfiles;
mXmlDocument.pa... | Besides the value of the node, also examine the type. If the type is rapidxml:::node_element or rapidxml:::node_document it may have children.
See the member function rapidxml::print_node in rapidxml_print.hpp.
|
6,646,643 | 6,646,727 | Autocompletion from stdin with clang | I have set up an environment for autocompletion in Emacs, using clang 2.8 as the parser. It works well, but relies on saving the currently edited buffer to file before completion. This is slow, so I am trying to get clang to parse a file given to it via stdin instead, without luck so far.
The command line I feed clang ... | Does it work if you specify -cc1 before -x c++?
|
6,646,702 | 6,646,887 | Get file name without extension? | I'm new to C++ world, I stuck with a very trivial problem i.e. to get file name without extension.
I have TCHAR variable containing sample.txt, and need to extract only sample, I used PathFindFileName function it just return same value what I passed.
I tried googling for solution but still no luck?!
EDIT: I always get ... | Here's how it's done.
#ifdef UNICODE //Test to see if we're using wchar_ts or not.
typedef std::wstring StringType;
#else
typedef std::string StringType;
#endif
StringType GetBaseFilename(const TCHAR *filename)
{
StringType fName(filename);
size_t pos = fName.rfind(T("."));
if(pos == StringType::np... |
6,646,861 | 6,649,481 | Determine address family of an unbound socket | When I try to bind my socket I need to specify the address family in the addrinfo/sockaddr-structure I pass in to the call to bind(), or one will get an winsock error 10047 (Address family not supported by protocol family.)
What if I created a socket elswhere not knowing its address family...
How could I get the addres... | Since I am using Winsock I did search the MSDN for a short while and found WSADuplicateSocket.
WSAPROTOCOL_INFO proto;
WSADuplicateSocket(Socket, GetCurrentProcessId(), &proto);
SocketAF = proto.iAddressFamily;
Works fine for windows machines...
|
6,647,038 | 6,647,093 | Intitialzing an array in a C++ class and modifiable lvalue problem | I have a basic C++ class .The header looks like this:
#pragma once
class DataContainer
{
public:
DataContainer(void);
~DataContainer(void);
int* getAgeGroup(void);
int _ageGroupArray[5];
private:
int _ageIndex;
};
Now inside the cpp file of the class I want to intialize the _ageGroupArray[5] with... | In the current standard, as you have already noticed, you cannot initialize a member array in the constructor with the initializer list syntax. There are some workarounds, but none of them is really pretty:
// define as a (private) static const in the class
const int DataContainer::_age_array_size = 5;
DataContainer::... |
6,647,383 | 6,647,770 | Can’t make child in Qtreeview using QStandardItemModel | After reading some examples I am still missing here something.
I have Qtreeview for view and QStandardItemModel for the data interface, also using QSortFilterProxyModel subclass but I don't know if its relevant.
This is my logic:
First I create the model with the QWidget as the parent:
QStandardItemModel m_model = ne... | That's not how QStandardItemModel works - to add a child, call appendRow(s)/insertRow(s) on the parent QStandardItem:
QStandardItem* child = new QStandardItem( tr("Child test") );
...
QStandardItem* parentItem = m_model->item( 0, 0 );
parentItem->appendRow( child );
|
6,647,478 | 6,647,661 | My 'body' class in SFML: How does it rotate member shapes correctly on its own? | Hey so i've made a 'body' class, which inherits from sf::drawable in SFML that holds shapes together so i can form more complicated shapes and figures. I found i had to do a few updates on each individual member shape at render time, based on what's happened to the body over-all since last render.
This included:
Rota... | My guess was confirmed by the SFML source code.
When you call target.Draw(*this) it eventually calls Drawable::Draw(RenderTarget& Target) const, which sets up a render matrix which has the rotation that you gave it with the Drawable::SetRotation call. Your virtual Render function is then called, with that rotation envi... |
6,647,500 | 6,647,622 | How to display precisely the decimal digits of a double in C++? |
Problem
Given two integers a, b, a < b. Display its decimal expansion. You will print the decimal expansion of integer quotient given, stopping just as the expansion terminates or just as the repeating pattern is to repeat itself for the first time. If there is a repeating pattern, you will say how many of digits ar... | The problem is that double doesn't have infinite amounts of precision, but instead can only manage about 16 decimal digits worth. Which is where you run into trouble (funny, that!) as the fundamental lack of information in the input double shows up.
You need to find a way of tackling the problem that will keep getting ... |
6,647,542 | 6,647,610 | borland c++ compiler won't undo memory allocation when exception thrown across constructor boundary? | I am using bcc32 command line compiler from Borland Embarcadero. Consider this program:
int main(int, char **)
{
try
{
std::string *a = new string(0xf0000000, ' ');
...
delete a;
}
catch(const std::bad_alloc &)
{
...
... | Either your compiler is broken, or something else funny is going on. The implementation is required to free the memory:
5.3.4/17:
If any part of the object initialization described above terminates by
throwing an exception and a suitable deallocation function can be
found, the deallocation function is called to fr... |
6,647,578 | 6,654,742 | System::String reference to C++ char* parameter | Is there an direct way to manage C++/CLI Strings in a wrapper to char* parameter for native C++ method?!
example:
void Test::TestFunc(System::String ^%str)
{
// right conversion to char* and consider the reference
}
native C++ function:
void TestB::Func(char *str)
{
...
}
my tricky way:
void Test::TestFunc(Sy... | You're doing a lot manually that the runtime will take care of for you.
void Test::TestFunc(String^% szRecvBuffer)
{
using System::Runtime::InteropServices::Marshal;
IntPtr memHandle = Marshal::StringToHGlobalAnsi(szRecvBuffer);
try
{
char* const str = static_cast<char*>(memHandle.ToPointer());... |
6,647,783 | 6,647,792 | Check value of least significant bit (LSB) and most significant bit (MSB) in C/C++ | I need to check the value of the least significant bit (LSB) and most significant bit (MSB) of an integer in C/C++. How would I do this?
| //int value;
int LSB = value & 1;
Alternatively (which is not theoretically portable, but practically it is - see Steve's comment)
//int value;
int LSB = value % 2;
Details:
The second formula is simpler. The % operator is the remainder operator. A number's LSB is 1 iff it is an odd number and 0 otherwise. So we che... |
6,647,862 | 6,652,778 | Boost Asio tcp::resolver: service not found | I'm trying to create an HTTP client using Boost Asio. I copied the sync client example from asio, compile, then run. Unfortunately, on my logs, it shows Service not found. When I traced the code, I found it that it is thrown from the following code:
boost::asio::io_service io_service;
// Get a list of endpoints corresp... | This means the OS does not know which port number corresponds to the TCP service with the name "http".
On a unix-like OS, this would mean the line http 80/tcp is missing from /etc/services, I am able to reproduce the error on Linux by commenting that line out.
If the OS cannot be configured to use services, you may use... |
6,647,953 | 6,647,987 | Displaying weird characters Turbo C++ | I have a little trouble in the display of heights for my program. This is what i wrote:
if (0 < LaserX < 161) {
LaserX = LaserX/n;
LaserY = LaserY/n;
sprintf(LaserMID, "%.1f, %.1f", LaserX, LaserY);
ShowCo->Text = LaserMID;
}
else { ShowCo->Text = 0; }
So basically it will show the height value when I have LaserX betw... | Below condition is not what you want,
if (0 < LaserX < 161) // evaluated from left thus always true (which is unwanted)
You can change it to,
if (0 < LaserX && LaserX < 161)
It precisely means that LaserX is greater than 0 and less than 161.
Edit: NaN = Not a Number.
|
6,648,277 | 6,648,505 | Assert won't display the error message | I'm having a weird problem with assert in Visual C++ 2005. I've tried to introduce asserts into my program and no matter what asserts I try to use (assert() or BOOST_ASSERT_MSG) it gives the exact same error message which tells me nothing other than that a debug error occurred.
Debug Error!
Program: ...
This applicati... | If you use Microsoft's _ASSERTE macro (note the E for Expression) then the message will also appear in assert dialog.
The reason both versions of ASSERT exist is that both have advantages and disadvantages and you get to choose which you want.
_ASSERTE gives better diagnostics but results in slightly bigger binaries (... |
6,648,403 | 6,648,422 | C++ : Writing doubles in a file with more precision than default | I want to write doubles to a file but the string cast reduces the precision.
Edit : I don't really cast but put the doubles in an ostringstream.
Is there another way than parsing each digit using modulo and division to write the doubles with more precision ?
Edit : My application needs to be portable
Here is my curren... | You can use precision function.
|
6,648,520 | 6,648,596 | How can I create template class member implementations in the cpp file for multiple types | I've got a template class called w32file which works with both wchar_t and char. It's declared:
template <typename T>
class w32file { ... }
And it has many member methods such as this one:
inline bool isDirectory();
Now I know I could put all the implementation of these member methods in the header file and they... | Define the function templated and use explicit template instantiation:
namespace w32utils
{
template <typename T>
bool w32file<T>::isDirectory()
{
const auto dwAttr = GetFileAttributes(m_name.c_str());
return ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
}
template class w32file... |
6,648,605 | 6,648,706 | Lightweight wrapper - is this a common problem and if yes, what is its name? | I have to use a library that makes database calls which are not thread-safe. Also I occasionally have to load larger amounts of data in a background thread.
It is hard to say which library functions actually access the DB, so I think the safest approach for me is to protect every library call with a lock.
Let's say I h... | You could make protectedCall a template function that takes a functor without arguments (meaning you'd bind the arguments at the call-site), and then creates a scoped lock, calls the functor, and returns its value. For example something like:
template <typename Ret>
Ret protectedCall(boost::function<Ret ()> func)
{
... |
6,648,725 | 6,648,778 | Boost thread example show error it's cannot matching function for call to 'boost::thread::thread(<unresolved overloaded function type>)' | I'm initialized thread on main function when created namspace multithread_init in order to push set_multihthread class to namespace. Why after declared boost::thread it's not matching function for call boost::thread t(smulti.thread)?
#define BOOST_THREAD_USE_LIB
#include <boost/thread.hpp>
#include <boost/thread/threa... | You can't pass a member function that way. You need to bind it to the object
boost::thread t(boost::bind(&multithread_init::set_multithread::thread, &smulti));
|
6,648,793 | 6,649,209 | Cannot use errno.h with gcc/g++ after updating ubuntu 10.4 | After updating Ubuntu 10.4, I'm not able to build any projects with errno.h used in them. EPERM, EINVAL,... are now "undeclared"
I tried tracking down the problem, and I think it's some messup with the gcc, or with ubuntu packages, because in /usr/include/linux/errno.h:
#ifndef _LINUX_ERRNO_H
#define _LINUX_ERRNO_H
#i... | On my Ubuntu 10.04 system, /usr/include/asm/errno.h is part of the linux-libc-dev package.
I suggest you perform a clean reinstall of that package.
|
6,648,828 | 6,648,854 | Passing 2D array as argument | In thsi example:
int a[2][2]={{1,2},{3,4}};
int *p=a[0];
cout<<p;
cout<<&a[0][0];
Both gives the same output.
Then why am I not able to call function (say fun)like this and loop through the array:
fun(a[0]);
fun(int *p)
{
cout<<p[1][1];
}
| fun(a[0]); //this looks OK
void fun(int *p) // this is OK if you add return type'
^^^^
{
cout<<p[1][1]; //NOT OK! You can't have 2 indices on an `int*`
cout << p[1]; // OK, will print a[0][1]
}
|
6,649,019 | 6,649,089 | Class similar to NSMutableDictionary in c++ | I want to create a class similar to NSMutableDictionary in c++. Which datatype can i use or is there any free library available in c++.
I can't use std::map because it stores only homogenous data... I want to store heterogeneous data, can i use Boost libraries. Which class(list here) in the boost library does operation... | There is no exact equivalent for NSMutableDictionary in C++ but std::map is probably what you can make best use of.
Reasons:
NSMutableDictionaryhas built-in reference counted memory management, while none of the STL container classes take ownership of the contained objects if they are pointers.
So at best the equival... |
6,649,572 | 6,649,620 | VC++ prevent all symbol name decorations | I'm working on a DLL which will be used from another language (so no import libs and including the dll's headers) using the _stdcall calling convetion. The problem is that VC++ seems to always do some name decoration on its exported symbols. All the references ive seen say use extern "C" but this still seems to leave m... | You can use a .def file. It will let you export the functions without the decorations.
Read: Exporting from a DLL Using DEF Files
|
6,649,641 | 6,649,717 | What optimization settings should I use for a C++ library | I want to write a (static) library for other programmers to use that uses the compiler's optimisations.
Whilst writing and testing the library using debug builds I find it runs quite slowly, but if I switch to a release build then it seems to be acceptably fast.
At the moment I've compiled the library as a debug build ... | This is the old problem of static libraries: it has to use the same CRT of the executable that links against it, otherwise the linker will find conflicting versions of the same CRT routines and data structures (both the public and the internal ones).
Since there are currently 4 versions of the CRT (all the debug/releas... |
6,649,852 | 6,649,914 | getline not working properly ? What could be the reasons? |
Possible Duplicate:
getline not asking for input?
There is some unique thing happening in my program.
Here are some set of commands :
cout << "Enter the full name of student: "; // cin name
getline( cin , fullName );
cout << "\nAge: "; // cin age
int age;
cin >> age ;
cout << "\nFather's Name: "; // cin fa... | Since you have not posted any code. I am going to take a guess.
A common problem while using getline with cin is getline does not ignore leading whitespace characters.
If getline is used after cin >>, the getline() sees this newline character as leading whitespace, and it just stops reading any further.
How to resolve ... |
6,649,874 | 6,649,894 | Equivalent of goto of c++ in Java in a specific scenario | I am replacing a old C++ code with Java:I know there is no equivalent of goto in java as it causes many surprising errors and unintended loop terminations.
C++ code: //I have skipped the actual code
for(//some condition){
if (excl(grds[i],0))
{
//do something
goto breakout;
}
//some more cod... | Yes, that would be the better way — in Java, and in C++.
|
6,649,936 | 6,649,992 | C++ compiling on Windows and Linux: ifdef switch | I want to run some c++ code on Linux and Windows. There are some pieces of code that I want to include only for one operating system and not the other. Is there a standard #ifdef that once can use?
Something like:
#ifdef LINUX_KEY_WORD
... // linux code goes here.
#elif WINDOWS_KEY_WORD
... // windows cod... | use:
#ifdef __linux__
//linux code goes here
#elif _WIN32
// windows code goes here
#else
#endif
|
6,649,939 | 6,656,482 | Use cmake to conditionally generate source input files | I'm using cmake with C++ project. I want to use precompiled headers in GCC.
I want to run cmake once and then, when running make, I want this actions to happen:
Run my custom tool (python script) on whole source tree. It generates precompiled.h headers in some subdirectories. It's purpose is to scan *.h and *.cpp for ... | The following CMake commands may serve as a starting point for your project:
add_custom_target(scanner COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scanner.py"
COMMENT "Scanning include files ..."
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
This command covers step 1. It invokes your python script which may updat... |
6,649,989 | 6,650,222 | COM : retrieve good CLSID | I have a little problem with the CLSID.
I have a (hooked) function which has in param a REFCLSID.
So I want to print this param.
I did:
LPOLESTR pOleStr;
StringFromCLSID(rclsid,&pOleStr); //rclsid is a REFCLSID type.
ofstream myfile;
myfile.open("C:\\output.txt",ios::app);
myfile << pOleStr << std::endl;
myfile.close()... | Just a guess, I think that LPOLESTR is widechar, you'd have to convert it to ASCII using
CHAR szCLSID[60];
WideCharToMultiByte(CP_ACP, 0, pOleStr, -1, szCLSID, 60, NULL, NULL);
Also don't forget to CoTaskMemFree(pOleStr) afterwards :)
|
6,650,236 | 6,650,265 | Two separate "if"'s, same condition -- is it OK? | Which of the two, do you think, is better?
if (the_condition)
{
variable = sth;
}
else
{
variable = sth_else;
}
if (the_condition)
{
variable_2.doSth();
}
else
{
variable_2.doSthElse();
}
or
if (the_condition)
{
variable = sth;
variable_2.doSth();
}
else
{
variable = sth_else;
variable... | #2
What if the condition changes? Then you'd have to update it in n places! (And it's easy to miss one, introducing subtle, hard-to-find bugs.)
I personally find #1 much harder to read, since I have to read the condition for each assignment because it might be different. With #2, I know that everything in the if body i... |
6,650,705 | 6,674,448 | Error handling: distinguishing between 'fatal' errors and 'unexpected input' errors | I've been working on a program that reads in an XML file, and if ifstream is unable to open the file, it will throw std::ifstream::failure. This exception is thrown whenever std::ifstream::failbit is set or std::ifstream::badbit is set, and they are (at least in my opinion) the type of errors that warrant exception han... | Your design makes good sense to me: Initialize completely or throw an exception. The only alternatives which come to mind are:
status codes
best-effort initialization with status member functions to find out what portions are valid
The only disadvantage which comes to mind for the all-or-nothing approach is dealing... |
6,651,013 | 19,953,737 | Detect emptiness of DVD-RAM media on Windows 7 x64 | I'm trying to detect if a DVD-RAM media is empty or not, with C++ on Windows. The simplest choice is to use IMAPI (version 2) - boilerplate code omitted:
IMAPI_FORMAT2_DATA_MEDIA_STATE state;
HRESULT hr;
// ... Initialize an MsftDiscFormat2Data COM object and put recorder
hr = format->get_CurrentMediaStatus( &state )... | You can use the method IDiscFormat2::get_MediaHeuristicallyBlank from IDiscFormat2 interface.
It will attempt to determine if the media is blank using heuristics (mainly for DVD+RW and DVD-RAM media).
VARIANT_BOOL vbBlank;
hr = format->get_MediaHeuristicallyBlank(&vbBlank);
if (VARIANT_TRUE == vbBlank)
Log("The me... |
6,651,107 | 6,651,318 | Why does generating pdb files increase the size of my native C++ exe? | Just by turning on Configuration Properties > Linker > Debugging > Generate Debug Info the size of my exe has increased from 2.11MB to 2.34MB
What is that extra ~230KB being used for? I thought the exe should be roughly the same size (give or take an extra path to the pdb file) but not that much. Would there be any pe... | The increase of size of the executable is probably due to the compiler including code that would have otherwise be optimized away. Try linking with /OPT:REF, and see if that drops the size back to around what it was.
As for the performance hit, it should not be significant. The bloat might cause caching of code to be l... |
6,651,268 | 6,651,418 | Boost error in xcode | I am new to boost library. I just dragged and drop the boost folder to xCode and entered the header search path. When i compile it is giving error
#if defined(BOOST_ASIO_HEADER_ONLY)
# error Do not compile Asio library source with BOOST_ASIO_HEADER_ONLY defined
#endif
How to fix this?
| You can't just drop the Boost source into Xcode and build it. Use the build instructions from the Boost documentation.
|
6,651,356 | 6,651,599 | Two buttons one window | I've got two push_buttons on dialog and both of them are meant to invoke QFileDialog window, with the difference that first button is for input files and second for output files, other than that logic is the same. What is the best way to connect those buttons to QFileDialog without doing any code repetion.
P.S.
Ideally... | IMO you should use two QFileDialog objects, one for each case. To make a difference between imput/output you should set the AcceptMode.
|
6,651,439 | 6,760,438 | Home button event in HTC Smart, delivered to my own app? | I want to get an event to my application when someone presses the Home button:
(The silvery button with an arrow pointing left is the Home Button on the HTC Smart.)
However, when I press the button, no event at all arrives to my app. If I connect the system logger, I see that the Brew MP OS itself detects something, b... | The app will first receive an EVT_KEY with wParam=63620 and then immediately get the EVT_APP_SUSPEND event.
Hence, as far as I understand, the "Home Button" can not be used in any meaningful way by Brew applications for input.
|
6,651,785 | 6,651,852 | Next_permutation and efficiency | Is it more efficient to begin with a possibly random ordering of objects in a range, using next_permutation to step through all greater permutations, followed by stepping down, beginning again with the original ordering, using prev_permutation to reach the last.
Or, to sort the range before permuting, then to use only ... | next_permutation will step through all permutations, not only through greater permutations. No need to revert and use prev_permutation, and certainly no need to sort.
You only need take care of the fact that next_permutation will return false once it “rolls over” into the lexicographically lowest permutation so you nee... |
6,651,787 | 6,652,029 | Static pointer won't initialize in the subclassed window procedure? | I am confused why the second static pointer pthis won't initialize? What I did is I subclass a window procedure through a static function. The first static pointer lpProcess was initialize in the main procedure. However, the second one won't even call its own constructor (I used debugger to determine this problem). Som... | Most C++ compilers emit a small code `preamble' for procedures that have static data like this. This preamble checks a (hidden) boolean flag, and initialises/constructs the statics if it's clear. The boolean flag is then set to indicate that the statics shouldn't be initialized again.
Not all compilers manage these fla... |
6,651,909 | 6,652,324 | C++ code to emulate virtually mapped network drive under Windows? | Here is the situation:
I have a RESTful web service which when queried returns a list of virtual files (file-name, size, last modified, creation date and an id). It is also possible to get the binary content data of any file using its id from the same web service.
What I want to do:
I want to write a piece of C++ code... | What you need is called "userspace file system". You can create one, for example, on top of Dokan library.
|
6,652,165 | 6,652,342 | Default values for arrays members of struct |
Possible Duplicate:
Intitialzing an array in a C++ class and modifiable lvalue problem
As seen in this question, it's possible to give a ctor to a struct to make it members get default values. How would you proceed to give a default value to every element of an array inside a struct.
struct foo
{
int array[ 10 ];... | Thew new C++ standard has a way to do this:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : array{1,2,3,4,5,6,7,8,9,10}, simpleInt(0) {};
};
test: https://ideone.com/enBUu
If your compiler does not support this syntax yet, you can always assign to each element of the array:
struct foo
{
int array[ 10 ... |
6,652,473 | 6,653,642 | Problem with IRC socket connection | Error occurs during JOIN and USER, it tells me I need to "Register first". The three: PASS, NICK work correctly (probably). Any idea how is this possible? I've followed the relevant RFC, https://www.rfc-editor.org/rfc/rfc1459#section-4.1
code:
#include <iostream>
#include <winsock2.h>
#include <string>
#include <cstrin... | I'm guessing that, to join that specific channel, your nickname must be registered with NickServ or equivalent IRC services. You'll probably have to register the nickname you're using with NickServ (I suggest using a regular IRC client to do this to make it easier) and then, from your code, PRIVMSG NickServ with some s... |
6,652,637 | 6,652,695 | Danger in using nested comments for quickly (de)activating code blocks in C++ | I'm currently using nested comments to quickly activate/deactivate code during testing, the way I'm doing it is like this :
//* First Case, Activated
DoSomething();
/**/
/* Second Case, De-Activated
DoSomethingElse();
/**/
I can activate, deactivate the code blocks by simply adding or deleting a '/'.
The compiler war... | This is how people normally do this:
#if 0
//...
#endif
or
#define TESTWITH
#ifdef TESTWITH
//..
#endif
|
6,652,934 | 6,653,140 | Regulating IPC between two processes with mutex | I am working on a project that creates two processes and I want to regulate the IPC between them.
The processes are created with the createProces function, and I want to use a mutex to do some IPC.
In Linux I do this with semaphores, however I have read that for IPC in Windows I have to use a mutex.
In windows I can't ... | You create anonymous Mutex using CreateMutex, then try to find it by name
|
6,653,040 | 6,653,256 | JNI pass parameters to method of c++ | I have a c++ file myCppTest.cpp which has method
int myFunction(int argv, char **argc) {
}
and
a Java native method in myClass.java
public native int myFunction (int argv, char[][] argc);
After generate the header file using javah -jni myClass, i have the header
JNIEXPORT jint JNICALL Java_JPTokenizer_init
(JN... | There is no direct mapping between Java objects and C++ primitives, so you will have to convert the arguments that are passed by the Java runtime environment, and then call your function.
Java will call Java_JPTokenizer_init -- this is where you perform your conversion and invoke your "plain old" C++ function.
To conve... |
6,653,237 | 6,653,466 | Scheduling huge number of threads so only 4 are executed in parallel | As already stated in the title I have a large number of threads (probably much higher than 100) that are rather saving a program state than running. I want only few of them (enough to use all physical processors) to really run concurrent and the rest should wait until one of the running is blocked. When this happens a ... | Just use a semaphore with initial count of 4?
http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_init.html
|
6,653,258 | 6,653,316 | Selecting Appropriate Data Structure | We are reading a book and we have to store every character of this book with it's count.
like : "This is to test" out should be: T4 H1 I2 S3 O1 E1
What will be the most appropriate data structure here and why? and what would be the logic here.
| An array of ints would do fine here. Create an array, each index is a letter of the alphabet (you'll probably want to store upper and lower case separately for perf reasons when scanning the book). As you scan, increment the int at the array location for that letter. When you're done, print them all out.
|
6,653,283 | 6,655,137 | Problem replacing boost::bind with std::tr1::bind | I have the following code which compiles and runs fine under Visual Studio 2008 SP1.
#include <functional>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/utility.hpp>
class NoncopyableObject : public boost::noncopyable
{
public:
Noncopya... | This appears to be a difference in how bind is implemented in MS Visual Studio (including 2010) and GNU gcc (I tested 4.4.1 and 4.5.2, both of which work the way you expected)
Consider the following code, given your definitions
auto b = boost::bind(&MenuItem);
NoncopyableObject obj(7);
b(obj); // OK in VS and GCC
rep... |
6,653,337 | 6,653,422 | At what point should I fight deep #include trees | I am currently working on a C++ project and am quite often using templates. Now I wonder if I should start worrying more about / cleaning up deep #include trees.
After removing not-needed includes, the code size after running the C preprocessor gcc -E on my .cpp files is:
50% of the files: ~40k lines,
30% of the file... | It doesn't matter how many lines of code there are. What matters is whether you feel build times are tolerable. If it takes too long to compile, then you need to speed it up, for example by eliminating unneeded includes.
But as long as you don't have a problem with build times, why bother worrying about whether you inc... |
6,653,557 | 6,653,823 | OpenCV / SURF tracking for iPhone: Wrong values when creating struct | I'm using the OpenCV library in Objective-C (cross-compiled), which works fine basically.
Unfortunately, when using the example which can be found in find_obj.cpp, I get strange values for the CvSURFParams that has to be passed as an argument to the cvExtractSURF function.
features2d.hpp (part of openCV):
typedef stru... | It sounds like the representation of the structure in OpenCV is different from how your ViewController.mm represents it. Either hessianThreshold is a different size, or else there is an alignment problem. Some things to check:
Output sizeof(CvSURFParams) in your ViewController.mm as some debug code. Also do this fr... |
6,653,726 | 6,653,773 | How to get info about crash from core file? | I have run a software and it crashed and left a core file. Now how I can read the info about crash by using core file?
| You can use the
$ gdb /path/to/application /path/to/corefile
Take a look at the gdb manpage for more information...
In this site you can have some information too.
|
6,653,798 | 6,653,851 | what is the best way of sharing a configuration object across classes? | Let us say that I have the classes M, A, B, C. M is the main class of my application (that is the one that does most of the job) and has this structure
class M {
public:
// Something here.
private:
Conifg config;
A a;
std::vector<B> bs;
const C* c;
};
In a main I create an instance m of class M... | I would advice you to use an additional static class for configuration, instead of static fields in all the classes, where you include its header in the places you want.
Implement a static constructor where you initialize all the data you want in the static members. I think this would be a better solution.
|
6,653,872 | 6,654,511 | Access Violation during planning of Fourier Transform | Little bit of background, I'm more experienced with Java, and have some C/C++ experience.
I'm using Visual Studios 2010.
I created two classes inside a header file and gave them fields.
It compiles ok, and for the longest time it was running just fine.
I copied the entire project directory to a new folder (all files ... | Access violation writing location 0x00000000 means that you're trying to write to memory location 0x00000000, i.e., you're writing to a null pointer. I think the pointer p probably has the value 0.
Possibly you're forgetting to call your Registration::setUpRegistration method?
|
6,653,971 | 6,782,004 | What's a small LGPL library for C++ UTF-8/UTF-16 text encoding? | Need something small and portable. Currently looking at UTF8-CPP but thought that I'd reach out for other suggestions too.
Cheers.
| UTF-8CPP it is, just want to mark this question as done with. Thanks for all the help guys :)
|
6,654,076 | 6,667,311 | Help with SNMP in C++? | I'm trying to write a simple program using WinSnmp in C++. There is very little information out there regarding this, and I am completely lost. All I want to do is query the printers on my network & read the info sent to me. Here is my code:
#include <WinSnmp.h>
#include <stdio.h>
smiLPUINT32 majorVers;
smiLPUINT32 m... | For out params like the ones to SnmpStartup, pass the address of UINT32s that will receive the values:
smiUINT32 majorVers;
smiUINT32 minorVers;
smiUINT32 nLevel;
smiUINT32 translateMode;
smiUINT32 retranslateMode;
SnmpStartup(&majorVers, &minorVers, &nLevel, &translateMode, &retranslateMode);
There may be more wrong... |
6,654,302 | 6,654,761 | Boost Random with templates | So I'm trying to use the Boost.Random mt19937 generator with templates. My c++ is a bit rusty, but from all I understand (and the doc, as always for Boost, is no less than vague) it should take a template argument that specifies it's return type (float / double).
I have no idea right now as to where the problem lies...... | generateNumber cannot be const - it permutes the Mersenne Twister. Make that mutable, or make the function non-const.
|
6,654,609 | 6,654,714 | Is this code broken or is there a bug in g++? | For some strange reason g++ (versions 4.5.0 and 4.5.2) cannot compile this code:
bool somefunc() {
return false;
}
class C {
public:
static const int a = 0;
static const int b = 1;
};
class myclass {
public:
int check() {
return somefunc() ? C::a : C::b;
// if(somefunc()) return C:... | There is an ongoing debate on whether this code is actually legal or not.
Either way, according to some readings the constants actually do need to be defined before usage, not just declared. That is,
class C {
public:
static const int a = 0;
static const int b = 1;
};
const int C::a;
const int C::b;
Or just... |
6,654,704 | 6,654,762 | Boost PropertyTree: How to read json array into? | So having such json:
{
"config": {
"name": "myconfig",
"servecies": {
"module": [
"file",
"Admin",
"HR"
],
"notModule": "MyNotModule"
}
}
}
How to parse module array into multimap<string,string>? and is it possible to find out if module is an array and notModul... | Use a JSON parser. There isn't really anything in C++ that will do all the work for you, you must use an external parser (or roll out your own) and interpret the events as it steps through.
I have had a good experience with jsoncpp, and there are a few others listed on json.org under the C++ section.
|
6,654,781 | 6,663,055 | Using COM dll in a Qt project | In vs c++ I used the following code to use some functions in a dll file that I don't have its header
#import "dll path"
HRESULT hr = CoInitialize(NULL);
if (hr==S_OK)
{cout<<"INITIALIZED\n";}
Trans_ATLLib::ITransCriptPtr Trans;
hr = Trans.CreateInstance(__uuidof(Trans_ATLLib::TransCript));
if (hr=... | If you use c++ - do the same! Qt is a set of libraries, not a different programming language - call to winApi everywhere you need, but don't forget that it is not portable.
|
6,654,878 | 6,654,900 | pass member function to QtConcurrent run() | I am trying to pass a member function to QtConcurrent::run()
I have tried to do it like so:
GDALDriver *poNITFDriver;
future = QtConcurrent::run(poNITFDriver,&GDALDriver::CreateCopy, pszDstFilename, poDataset, FALSE, papszOptions, pfnProgress, NULL);
but I get a slew of errors regarding no matching function call.
Thi... | You will have to pass a pointer of the object as the first argument and the address of the method as the second argument (then follow it by any other arguments).
Have a look at this documentation. Have a look at the sections:
Using Member Functions
Using Lambda Functions
Specifically, you can use boost::bind() or s... |
6,654,963 | 6,655,085 | How does overloaded template function selection (pattern matching) work in std::vector insert? | Consider the following declarations of a std::vector (taken from cplusplus - EASTL has the same declarations)
iterator insert ( iterator position, const T& x );
void insert ( iterator position, size_type n, const T& x );
template <class InputIterator>
void insert ( iterator position, InputIterator first, In... | Out of curiosity, I had a look at the GCC sources:
template<typename _InputIterator>
void
insert(iterator __position, _InputIterator __first,
_InputIterator __last)
{
// Check whether it's an integral type. If so, it's not an iterator.
typedef typename std::__is_integer<_InputItera... |
6,655,202 | 6,670,937 | Language for non-unicode programs and registry settings | Windows XP has a "Current language for non-Unicode programs" option in the Control Panel / Region and Language Settings.
One can use this to get non-unicode programs to respond to the selected language.
However there are some programs that don't respond to this setting and instead need registry changes to work. The reg... | The registry keys you mentioned does nothing but map some code pages to CP1251 (Cyrillic) effectively forcing CP1251 to be used throughout a system. So actually the program you mention has some of information hardcoded.
Unfortunately, you haven't gave us much information on what is your real challenge, so I am assuming... |
6,655,306 | 6,684,564 | Window regions, moving children, DWM, and the white blocky mess it can create | The setup: I have a top-level window with a region defined (created with SetWindowRgn()), and I have a child element that is moved (with SetWindowPos()) such that some of its pixels then overlap the clipped portion of the parent's window region.
The result: Those pixels become filled with fully opaque, fully white pixe... | I hate to answer my own question again, but I've found a work-around. I found that setting the window's region again clears any of the stray white pixels without causing any ugly redrawing or flashing anywhere else. This works even if the region I am setting is the same as the existing region, so something as simple ... |
6,655,338 | 6,655,360 | Where are static class variables stored in memory? | This is a follow-up question to How are static arrays stored in Java memory? .
So global variables in C/C++ are stored in the static data segment of memory. But what about static class variables in Java/C++?
It can't be the static data segment because you don't know what/how many classes are going to be referenced thro... | In Java, at a low level, class static variables are indeed stored on the heap, along with all other class metadata. To Java, they look like globals, but to the JVM's low level heap management routines, they're dynamic data (although they may be treated slightly specially in order to improve GC efficiency, since they're... |
6,655,370 | 6,655,520 | Invoking VS debugger on process crash vista-win8k | On xp, every time a process would crash the OS would pop up a dialog asking if I would like to debug the process. I cant find a way to enable this functionality on the later version of windows. So to reiterate, I want to attach a debugger to a native process that's auto broken on a crash.
Does anyone know how to get th... | Enable Just-In-Time debugging.
Edit: since that doesn't work for you, some additional suggestions -
Make sure the AeDebug registry key values are correct.
Setup WER to create full crash dumps, and debug the dumps.
Not sure about this, but is it possible your user doesn't have debug permissions? Have never checked that... |
6,655,601 | 6,655,626 | Is this a valid assignment in C++? | While I was looking at the library code, I found the below line
int number = config.nodes,i,fanout=numP/2;
I assume config is a pointer to something, but can there be commas in the statement? and make assignment like that?
| This declares three variables. It's the same as:
int number = config.nodes
int i;
int fanout = numP/2;
Please note that commas are handled specially in declarations (and argument lists), C++ also has a "comma operator" which is not being used here.
|
6,655,860 | 6,656,015 | C/C++ fastest cmath log operation | I'm trying to calculate logab (and get a floating point back, not an integer). I was planning to do this as log(b)/log(a). Mathematically speaking, I can use any of the cmath log functions (base 2, e, or 10) to do this calculation; however, I will be running this calculation a lot during my program, so I was wondering ... | Since b and a are integers, you can use all the glory of bit twiddling to find their logs to the base 2. Here are some:
Find the log base 2 of an integer with the MSB N set in O(N) operations (the obvious way)
Find the integer log base 2 of an integer with an 64-bit IEEE float
Find the log base 2 of an integer with a ... |
6,655,883 | 6,655,988 | Parsing C Header Files | I have a C header file that I have precompiled using the gcc -E flag, and am now trying to parse using Lex and Yacc; however, it is getting hung up on typedef'd variables.
for example:
typedef unsigned long ULONG;
ULONG i = 5;
will throw a syntax error at the second line's ULONG.
I have tried to redefine part of the g... | In the code you link too:
http://www.quut.com/c/ANSI-C-grammar-y.html,
look at the bottom:
You will see this function
int check_type(void)
{
/*
* pseudo code --- this is what it should check
*
* if (yytext == type_name)
* return TYPE_NAME;
*
* return IDENTIFIER;
*/
/*
* it actually will only retur... |
6,655,904 | 6,655,994 | How do I find the memory address of a string? | I am having a mental block and I know I should know this but I need a little help.
If I declare a string variable like this:
string word = "Hello";
How do I find the memory address of "Hello"?
Edit: This is what I am trying to do...
Write a function that takes one argument, the address of a string, and prints tha... | Use either:
std::string::data() if your data isn't null-terminated c-string like.
or
std::string::c_str() if you want the data and be guaranteed to get the null-termination.
Note that the pointer returned by either of these calls doesn't have to be the underlying data the std::string object is manipulating.
|
6,655,955 | 6,655,973 | C++: Is it possible to get a std::string out of an object that overloads the << operator? | I have an object that can be printed to the console with std::cout << obj, but I can't get a std::string out of it, because it doesn't seem to implement something like a .string() method. I thought I might be able to use that overloaded operator to just get string representations of everything instead of having to impl... | Use a std::ostringstream. It is a C++ stream implementation which writes to a string.
|
6,656,246 | 6,656,295 | C++ endl with constants | I am just trying to familiarise myself with the basics of C++ moving from Java. I just wrote this functionality abstinent program and am coming across an errortest.cpp:15: error: expected primary-expression before ‘<<’ token and I am not sure why.
Anybody care to explain why endl is not working with constants? The code... | You have a ; in your preprocessor definition. Note that #DEFINE STRING x just copies the whole x-statement (including the ;) into the place where it's referenced.
Also, a preprocessor constant isn't a language constant. You should use const string STRING("C++ is working on this machine usig the GCC/G++ compiler");
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.