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 |
|---|---|---|---|---|
5,074,763 | 5,078,420 | save the printable documetns in PCL-5e format using printer driver | I want to develop a printer driver which should save the printable data into given location in PCL-5e format.
I have gone through bitmap example which comes with WDK example set. According to that sample, If we want to dump bitmap file output we need to hook OEMEndDoc function and this will return SURFOBJ GDI structure... | No GDI structure will give you PCL5e data. PCL5e is a printer description language (PDL) that is understood by your printer and not by Windows GDI.
However, the GPD based drivers (Microsoft Unidrv) do have support for PCL5e so this can be used for creating PCL5e job output.
You can use any of the WDK sample GPDs itself... |
5,075,164 | 5,075,587 | How to hint to Visual C++ compiler optimizer that a specific branch of an if-statement is unlikely to be executed? | We have a macro for error-checking that goes like this:
#define CheckCondition( x ) \
if( x ) { \
//okay, do nothing \
} else { \
CallFunctionThatThrowsException(); \
}
and normally the condition has to be true and we'd like the CPU branch prediction to always select this path, and if it happens... | Not in MSVC, unfortunately, according to their developer center.
It's very frustrating because we'd like to use it in a couple of cases where the equivalent GCC intrinsic has saved us a critical few microseconds in inner loops, but the closest we can get is to swap the if and else clauses so that the more likely case i... |
5,075,192 | 5,075,359 | Another problem with decltype | template<class IntT, IntT low = IntT(), IntT high = IntT()>
struct X
{
static_assert(std::is_same<decltype(low),decltype(high)>::value,"Different types not allowed");//this should give error if types are different
decltype(low) a;
decltype(high) b;
X():a(decltype(a)()),b(decltype(b)())//WHY THIS DOES N... | First thing of note, VS2010 is outdated and was broken the day it was released. The decltype keyword was especially problematic and only works for the most basic of uses. In fact it gets a lot of basic things quite wrong.
Next the code...
template<class IntT, IntT low = IntT(), IntT high = IntT()>
struct X
{
sta... |
5,075,325 | 5,075,792 | C++ headers - Why would a program include both iostream and ostream? | I saw some programs including <iostream> and <ostream> simultaneously. Why?
Thanks for your kind reply.
| <iostream> is not the combination of <istream> and <ostream>. It merely defines std::cin, std::cout and related objects. To actually do anything useful with std::cout, you still need <ostream>. Now, by C++ rules it's possible that some implementations actually do include <ostream> in <iostream>, but you shouldn't rely ... |
5,075,374 | 5,075,408 | Iterators and templates | I'm trying to implement a function which allows the user to input some type of begin and end iterator, then all perform some operation on the data. However, the function has to be generic enough it should work for many types of iterators (for example std::vector::iterator, std::string::iterator, std::iterator, etc.). T... | template < typename Iter >
void fun_impl(Iter begin, Iter end, std::forward_iterator_tag)
{
// do your stuff here...
}
template < typename Iter >
void fun(Iter begin, Iter end)
{
fun_impl(begin,end, std::iterator_traits<Iter>::iterator_category());
}
The types returned by begin() and end() for various containers ... |
5,075,847 | 5,076,156 | Is there any cross-platform lib to work with shell (cmd in windows) via c++? | Looking for cross-platform lib to work (run scripts, process results) with shell (cmd in windows) via c/c++?
Please tell anything else than <cstdlib>'s system(). I want to know if there is anything with higher level and easy for use.
| I have used boost.process since 0.1
It is not officially included in boost mainstream, but seems to have reached a well tested state and seems to be on the point to be included.
my2c
|
5,075,928 | 5,076,090 | C++what is the type of the __LINE__ macro | As you may see from my other questions many of you may already got the answer for this. Can you please share that knowledge to me?
| C++03 §16.8p1:
__LINE__ The line number of the current source line (a decimal constant).
This will either be int, or if INT_MAX (which is allowed to be as little as 32,767) is not big enough (… I won't ask …), then it will be long int. If it would be bigger than LONG_MAX, then you have undefined behavior, which, for... |
5,076,206 | 5,076,640 | Is there a legal way to print tuples and pairs using operator<<? | I have a set of templates/functions that allow me to print a tuple/pair assuming that each type in the tuple/pair has operator<< defined for it. Unfortunately, due to 17.4.3.1, it is illegal to add my operator<< overloads to std. Is there another way to get ADL to find my operator<<? If not, is there any actual harm in... | Put your own light wrapper class around it and then overload operator<< to use that. However beware that even if your light wrapper has an implicit constructor you will probably still need to use it explicitly when you pass it to operator<<
template< typename ...VA_ARGS >
struct format_tuple
{
typed... |
5,076,226 | 5,076,299 | Covariant virtual functions return type problem | I have following code:
#include <iostream>
using namespace std;
class Child1
{
int i;
};
class Child2 : public Child1
{
int j;
};
class Base1
{
public:
virtual Child1& getChildren()
{
cout << "Children1" << endl;
return children;
}
private:
Child1 children;
};
class Base2... | You missed the other part they quoted: "If a function D::f overrides a function B::f, the return types of the functions are covariant if they satisfy the following criteria: (1) both are pointers to classes or references to classes"
|
5,076,318 | 5,078,647 | Linking error when calling a function that takes a vector of objects as it's argument | I have a function that takes a vector of objects as it's argument. the function header is:
void Evolve(vector <C_Agent> &population)
the code compiles properly as long as I don't try to actually call the function. I call it like this:
vector <C_Agent> AgentPopulation;
for(int q=0; q < x; q++)
AgentPopulation.pus... | nm from binutils is your friend. It will tell you what symbol main.o is trying to reference and what symbol the other object file, with the compiled function definition in, is actually making public. The mismatch between the twain will lead you to the cause of the mismatch, and thence to the solution to your problem.... |
5,076,472 | 5,079,285 | How can I format a std::string using a collection of arguments? | Is it possible to format std::string passing a set of arguments?
Currently I am formatting the string this way:
string helloString = "Hello %s and %s";
vector<string> tokens; //initialized vector of strings
const char* helloStringArr = helloString.c_str();
char output[1000];
sprintf_s(output, 1000, helloStringArr, toke... | You can do it with the Boost.Format library, because you can feed the arguments one by one.
This actually enables you to achieve your goal, quite unlike the printf family where you have to pass all the arguments at once (i.e you'll need to manually access each item in the container).
Example:
#include <boost/format.hp... |
5,076,618 | 5,171,292 | Windows event log service holding executable file handle | I have a service application that on startup and shutdown logs an event log record.
I rebuild the application frequently and also then the executable on the host machine. And here is the problem, after my service shutdown the Windows Eventlog service (not the event log viewer) is holding an open handle to the executab... | I think it is probably the event log viewer. Close the viewer and you'll be fine.
|
5,076,695 | 5,077,264 | How can I iterate through every possible combination of n playing cards | How can I loop through all combinations of n playing cards in a standard deck of 52 cards?
| You need all combinations of n items from a set of N items (in your case, N == 52, but I'll keep the answer generic).
Each combination can be represented as an array of item indexes, size_t item[n], such that:
0 <= item[i] < N
item[i] < item[i+1], so that each combination is a unique subset.
Start with item[i] = i. ... |
5,076,749 | 5,080,264 | Can I assume heap was not corrupted if _heapchk() returns "okay"? | In Visual C++ using new[] to allocate an array of objects and then delete (not delete[]) by default triggers undefined behavior of the following kind.
Calling destructors for all objects requires knowing the number of objects, so Visual C++ calls ::operator new[]() to allocate a slightly bigger buffer, puts the number ... | From the documentation (emphasis mine):
The _heapchk function helps debug heap-related problems by checking for minimal consistency of the heap.
It does not check for absolute consistency and correctness: it should be able to detect major, egregious errors, but it isn't going to catch every error.
|
5,076,964 | 5,077,061 | Owner-drawn button with BS_AUTORADIOBUTTON style | How do I get the checked/unchecked state of BS_AUTORADIOBUTTON? My code currently doesn't work.
void CPngButton::DrawItem( LPDRAWITEMSTRUCT lpDIS )
{
ASSERT(lpDIS != NULL);
UINT state = lpDIS->itemState;
if (state & ODS_CHECKED)
{
// do stuff
}
}
I've also tried
if (BST_CHECKED == SendMessage... | ODS_CHECKED only applies to menus. BM_GETCHECK and BM_GETSTATE can both provide the checked state:
if (Button_GetState(lpDIS->hwndItem) & BST_CHECKED)
|
5,077,018 | 5,077,348 | How local constants are stored in c++ library files | I am writing a library where I need to use some constant integers. I have declared constant int as a local variable in my c function e.g. const int test = 45325;
Now I want to hide this constant variable. What it means is, if I share this library as a .so with someone, he should not be able to find out this constant v... | If I understand right, you're not so much worried about an exported symbol (since it's a plain normal local variable, I'd not worry about that anyway), but about anyone finding out that constant at all (probably because it is an encryption key or a magic constant for a license check, or something the like).
This is som... |
5,077,019 | 5,077,103 | Best way to join and store a char string with a wchar_t string in c++ | C++ newbie here.
I have 3 strings
const char section1[] = {0x12, 0x34, 0x56, 0x78};
std::wstring section2 = L"section2";
const char section3[] = {0x23, 0x45, 0x67, 0x89};
And I need to join them together with a result that looks like
{0x12, 0x34, 0x56, 0x78, 0x73, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x69, 0x00, ... | std::vector<unsigned char> Buffer;
for (size_t i = 0; i < sizeof(section1); ++i)
Buffer.push_back((unsigned char) section1[i]);
for (size_t i = 0; i < section2.size(); ++i) {
unsigned short u = (unsigned short) section2[i];
Buffer.push_back((unsigned char) (u >> 8));
Buffer.push_back((unsigned char) (u & 0xFF... |
5,077,037 | 5,078,153 | How to access boost::variant members from Spirit::Qi rule? | I can't find a proper way how to access members of boost::variant using boost::phoenix in my Spirit-Qi grammar. Here is simple an example what I’m trying to achieve. (my whole grammar is much more complex, this is simple fragment where I'm testing mentioned problem).
namespace ph = boost::phoenix;
typedef boost::varian... | It's fairly easy to write your own 'lazy' Phoenix function. Here is one for boost::variant.
#include <boost/variant.hpp>
#include <boost/spirit/include/phoenix.hpp>
template <typename Result>
struct get_impl
{
template <typename T>
struct result
{
typedef Result type;
};
template <BOOST_VA... |
5,077,084 | 5,147,542 | My program crashes in boost::thread::thread_start_function, how can I debug | I've build C++ program using Visual Studio 2008. Both release and debug version are crashing at random times. The frequency of the crashes depends on the machine it runs on (from once a week to every hour).
The program uses boost asio for TCP communication as well as wxWidget for UI. Nevertheless the crashes are not re... | Considering I had a std::out_of_range, I looked at all my call to the at function.
And here it was:
std::string temp;
... ; if (temp.size() >= 8) temp.at(8) = '0'
Which should have been:
if (temp.size() >= 9) temp.at(8) = '0'
I still don't understand why I did not have more debug information on this exception, in debug... |
5,077,205 | 5,080,171 | C++ Qt window positioning | Does Qt has something to offer for the positioning of the tooltip-like windows? (or any types of windows/widgets actually).
I want to be able to update the position of the window automatically, so that it always stays on the screen (or at least fits it as much as possible).
An example of the behaviour I want can be see... | I don't know if Qt has one single function that ensures a widget is totally inside of the screen. But with QDesktopWidget it's probably trivial to do.
void function RestrainWidgetToScreen(QWidget * w)
{
QRect screenRect = QDesktopWidget::availableGeometry(w);
if(w->frameGeometry().left() < screenRect.left()) {
... |
5,077,513 | 5,086,534 | QDataWidgetMapper autosubmit doesn't work | I have created a sqldatabase and populate it with some test data. I'm using a QDataWidgetMapper and I think I've connected right because I can read the test records with this code:
databaseManager = new DatabaseManager();
dataMapper = new QDataWidgetMapper();
dataMapper->setSubmitPolicy(QDataWidgetMapper::A... | When you're setting submit policy for QDataWidgetMapper it defines the way how data is going to get transfered from the widget to the corresponding field of your model. AutoSubmit will transfer data to the model whenever widget looses focus. You should be able to track down changes to your model if would define a handl... |
5,077,693 | 5,079,785 | dirname(php) similar function in c++ | is there is any function in c++ ,similar to dirname in php...it is used to normalize the url
eg
<?php
$url = "../tets/index.html";
$currentURL = "http://example.com/somedir/anotherdir";
echo dirname($currentURL).substr($url, 2);
?>
| No, but implementing it yourself is trivial.
std::string DirName(std::string source)
{
source.erase(std::find(source.rbegin(), source.rend(), '/').base(), source.end());
return source;
}
Even better would be to implement it as a method template:
template<typename string_t>
string_t DirName(string_t source)
{
... |
5,077,726 | 5,077,820 | Low coupling and tight cohesion | Of course it depends on the situation. But when a lower level object or system communicate with an higher level system, should callbacks or events be preferred to keeping a pointer to the higher level object?
For example, if we are working on a game, we have a world class that has a member variable vector<monster> mons... | It generally is preferrable to use callbacks to communicate with higher level classes for the reasons you mention and to avoid mutual/cyclic dependencies.
In your case, you still have to define what is the lower level module. Should world really need to know what a monster is? Aren't monster just creatures or opponen... |
5,077,753 | 5,077,825 | How can i create a new object in a class?(c++) | Good evening every body~
As the title, How can i create a new object in a class? and i want to give it a number.
How can i do that?
Thank you very much~
| class MyClass {
int yourNumber;
};
or what do you mean?
|
5,077,920 | 5,077,953 | C++ Array of function pointers: assign function using char | I have an array of function pointers like this:
void (*aCallback[10])( void *pPointer );
I am assigning functions to the array like that:
aCallback[0] = func_run;
aCallback[1] = func_go;
aCallback[2] = func_fly;
The names like "run", "go", "fly" are stored in another array.
Is it possible to assign the functions to t... | Not directly, no. The symbol table and other meta-information is generally not available at runtime, C++ is a compiled language.
The typical way to solve it is to use some macro trickery, perhaps along the lines of this:
/* Define a struct literal containing the string version of the n parameter,
* together with a poi... |
5,078,082 | 5,078,304 | Why aren't my hyphens displaying correctly using std::cout? | I am trying to print out the following string using std::cout :
"Encryptor –pid1 0x34f –pid2"
the '-' characters appear as u's with a circumflex above them (I'm not sure how to type this).
How do I print out the hyphen as intended?
| That was not a hyphen.
It was a "n-dash", which will render differently across consoles based on encoding settings.
The hyphen key is usually on the number row of your keyboard, on Western layouts.
|
5,078,183 | 5,078,310 | Memory leak tracing with AppVerifier | I have a C++ application that has some minimal leaks, and I would like to fix them. I am using AppVerifier to dump the leaked objects, and I can get the addresses and first few bytes of the allocated memory.
Unfortunately, those first bytes and raw address is not enough to pinpoint the allocation stack trace, is there ... | With the gflags utility you can enable storing call stack information (gflags +ust). However, your applications will now run slower and take more memory.
Side-remark: To be honest, I never got all those Microsoft utilities (leak-tracing in the C-RunTime, Gflags, UMDH, AppVerifier, LeakDiag) to do exactly what I wanted... |
5,078,387 | 5,079,668 | OpenCV - Access to pixels along the curve/path | is there any way to access pixels along the specified curve/path in OpenCV?
I've found LineIterator:
http://opencv.willowgarage.com/documentation/cpp/core_drawing_functions.html?highlight=lineiterator#LineIterator
but it's limited to lines. I would like to find something similar to LineIterator, but working with circle... | It is not builtin to opencv, but you can use http://en.wikipedia.org/wiki/Midpoint_circle_algorithm for circles, the article also mentions a paper that describes an extention to ellipses.
|
5,078,434 | 5,093,854 | Type Qualifiers for a device class in CUDA | I'm currently attempting to make a piece of CUDA code with a class that will be used solely on the device side (i.e. host doesn't need to know of it's existence). However I cannot work out the correct qualifiers for the class (deviceclass below):
__device__ float devicefunction (float *x) {return x[0]+x[1];}
class dev... | It turns out the qualifiers have to go on the member functions of the class, below is a fully working version:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void Cleanup(void);
// Functions to be pointed to
__device__ float Plus (float a, float b) {return a+b;}
class deviceclass {... |
5,078,449 | 5,078,516 | Difference between pointer and array |
Possible Duplicates:
Difference between char *str=“STRING” and char str[] = “STRING” ?
C: differences between pointer and array
Hi,
Can anybody tell me the difference between the statements below?
char *p = "This is a test";
char a[] = "This is a test";
| When you declare char p[] you are declaring an array of chars (which is accessible to be both read and written), and this array is initialized to some sequence of characters i.e. "This is test" is copied to the elements in this array.
When you declare char* p, you are declaring a pointer that points directly to some co... |
5,078,626 | 5,078,745 | JSONify string in C++ | In my program I need to output simle JSON data. I looked at many libraries for JSON in c++, they are too complex for my task. Is there some easier way, how to create JSON-safe string from any c++ string?
string s = "some potentially dangerous string";
cout << "{\"output\":\"" << convert_string(s) << "\"}";
How would f... | If your data is in UTF-8, per the string graph on http://json.org/:
#include <sstream>
#include <string>
#include <iomanip>
std::string convert_string(std::string s) {
std::stringstream ss;
for (size_t i = 0; i < s.length(); ++i) {
if (unsigned(s[i]) < '\x20' || s[i] == '\\' || s[i] == '"') {
... |
5,078,679 | 5,078,707 | What is the scope of a pragma directive? | What is the scope of a pragma directive? For example, if I say #pragma warning(disable: 4996) in a header file A that is included from a different file B, will that also disable all those warnings inside B? Or should I enable the warning at the end of file A again?
| It is till the end of the translation unit. Informally, a TU is the source file with its include files.
The usual pattern is this:
#pragma warning (push) //save
#pragma warning (disable: xxxx)
#pragma warning (disable: yyyy)
...
//code
#pragma warning (pop) //restore prev settings
for example
//A.h
#pragma once
#pra... |
5,078,765 | 5,078,951 | Device detection connected to PC using C++ | How can I detect the connected devices into a Computer using C++? I can use windows programming facility, but .Net functionality is not allowed.
Thanks in advance.
| Try to handle WM_DEVICECHANGE message. When wParam = DBT_DEVICEARRIVAL, new device is detected.
|
5,079,168 | 5,285,118 | Setting current/compatibility version for a dylib using Netbeans (linux/mac) | As per the title, how can I set those? Moreover, how can I set versions themselves?
Thanks to all and best regards.
| I believe you can add build options to your project. You'd need to add linker options to set the compatible and current versions according to this page on "Mac OS X for for Unix Geeks": library version. (They use a library called "answer" in their examples, with a supposed current version of 1.2.6)
-dynamiclib -install... |
5,079,175 | 5,079,193 | Adding a timer in a C++ loop | I found some simple Pi calculation programs written in C++. My knowledge of C++ isn't that good(none to be exact), but how do i go about implementing a timer to tell me how long it took for the program to calculate the Pi number?
Like: Pi calculation finished in X seconds or minutes or hours etc.
| #include <cstdio>
#include <ctime>
using namespace std;
int main()
{
clock_t start = clock();
/* Code you want timed here */
printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);
}
|
5,079,196 | 5,079,256 | Open file with another application | Hy!
I want to open an .xml file from c++ with a specified application (knowing the path of the file and the path of the application). Same way as you would right-click the file and click "Open with..." and choose the application to start with.
Thanks in advance!
| Usually applications allow command line arguments for file opening. For example, to open a file with notepad you can use command line :
notepad.exe a.txt
That's why you can use this feature with CreateProcess in Windows (which allows specifying arguments) or analogous function in other OS . HTH
|
5,079,325 | 5,079,548 | Should I include stddef.h or cstddef for size_t | When I want to use size_t in C++, should I include <stddef.h> or <cstddef>? I have heard several people saying that <cstddef> was a bad idea, and it should be deprecated. Why is that?
| I prefer #include <stddef.h>.
Some of the names in the C headers are allowed to be macros, but the set differs from the C rules. In C, EXIT_FAILURE, isdigit(), getc() a.o. are macros. Do you know which ones are macros in C++?
Secondly, only a couple standard C headers are required to have the <cfoo> header, Posix heade... |
5,079,372 | 5,079,504 | Virtual friend functions and template explicit specializations | I'm trying to simulate the effect of a virtual friend function by using a protected virtual member function (http://www.parashift.com/c++-faq-lite/friends.html#faq-14.3).
In addition, I use explicit specializations for my templated classes. I was wondering if somebody could shed some light to understand what I'm doing ... | template < class T, class U > void applyOnBar( const CFoo<T, U> &, const CBar<U> );
That lacks an & on the second argument, should be:
template < class T, class U > void applyOnBar( const CFoo<T, U> &, const CBar<U> & );
Next,
virtual void do_applyOnBar(const CBar<U> &);
This one needs a const, since you use refFoo.... |
5,079,509 | 5,086,356 | get xorg.conf serverLayout with c++ | I am currently working on a multi window application that spans over multiple screens. The software is written with xlib and runs on ubuntu 10.10, gnome desktop.
To get the position of every window I'd like to access the /etc/X11/xorg.conf file, expecially the section SeverLayout. It looks somehow like this:
Section "... | Information about layout of multiple monitors in X, especially when they're combined into a single logical screen, is available via the libXrandr and libXinerama API's. Unfortunately, the multi-screen API's added to libXrandr in version 1.2 aren't covered in the man page, but require looking at the extension spec and... |
5,079,635 | 5,283,690 | How can i use tesseract ocr(or any other free ocr) in small c++ project? | So what I heard after research is that the only solid free OCR options are either Tesseract or CuneiForm.
Now, the Tesseract docs are plain horrible, all they give you is a bunch of Visual Studio code (for me on Windows) and from there you are on your own in an ocean of their API. All you can do is use the exe that co... | You might have given up, but there may be some other who are still trying. So here is what you need to start with tesseract:
First of all you should read all the documentation about tesseract. You may find something useful is the wiki.
To start using the API(v 3.0.1, currently in trunk, read also the README and Chan... |
5,079,639 | 5,079,657 | Informix OIC++ : query yields error MI_LIB_USAGE / Argument (client library error) is NULL | Using Informix C++ interface, the first query is fine, but the second yields this error
MI_LIB_USAGE: XIX000:-7520:Argument (client library error) is NULL.
My code
// connection okay and open
ITQuery query(conn);
string qtext;
qtext = "SELECT * FROM transit_kunde_s WHERE erledigt='N'";
okay = query.ExecForIteration(... | solution is to use a fresh query object:
ITQuery query_up(conn);
code = query_up.ExecForStatus(qtext.c_str());
EDIT: And if one want transaction enabled one has to use a fresh connection! See [http://stackoverflow.com/questions/5095519/how-to-use-transactions-in-informix-csdk]
|
5,079,847 | 5,079,875 | size of a user defined class | why the size of the class cl1 in the following code is 8 but not 5, while the size of class cl2 is 1?
class cl1 {
public: ... | The compiler is free to insert padding in between and after class members in order to ensure that variables are properly aligned, etc. Exactly what padding is inserted is up to the implementation. In this case, I'd guess that the compiler is adding 3 bytes of padding after cl1::cb, perhaps to ensure that the next var... |
5,079,877 | 5,117,552 | Alternative to secondary expansion in a makefile for GNU make 3.79.1 | I've been working on a makefile that uses secondary expansion not knowing that this feature only exists since version 3.81 of GNU make. Unfortunately, there are some old machines around here that only have make 3.79.1 installed and on these machines, the makefile doesn't work, of course. Is there an alternative to seco... | Just add make-3.81 sources in your source tree. Your main Makefile first should compile make-3.81 using whatever make is available and then use make-3.81 for compiling everything else.
|
5,080,116 | 5,080,147 | Flexible class behavior in C++ | I need to write a class in C++ that would represent an abstraction of a calculation. That class will have a function that will run an actual calculation.
class Calculation {
Calculation() {}
~Calculation() {}
Calculate(); //member function that runs a calculation
};
I need that class to be able to represe... | You can make Calculate virtual and create child classes that implement the varying behavior you need.
|
5,080,129 | 5,099,008 | server name of MAPI account | how can I find out the server name of a MAPI account for Microsoft Exchange Server? Thank you!
|
Under Outlook 2010, read the PR_EMSMDB_SECTION_UID property. If the property is missing or if using an older version of Outlook, assume pbGlobalProfileSectionGuid.
Use the GUID from (1) to call IMAPISession.OpenProfileSection().
Read PR_PROFILE_HOME_SERVER property from the IProfSect object returned from (2)
You can ... |
5,080,233 | 5,080,279 | Where is WIN32 defined, and how can I include this definition in my project? | I am including a third party header and source file into my project.
At the top of the header there is this:
#if defined(WIN32) || defined(WIN16)
#ifndef MSDOS
#define MSDOS
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#ifndef MSDOS
#include <unistd.h>
#endif
#include "des.h"
The problem is that #if defined(... | Depends on your project setup. WIN32 is defined inside the windows header files, but you can pass it to the compiler as well ("-DWIN32" for gcc for example). Try it and see whether it compiles.
|
5,080,253 | 5,080,408 | getting thread name from thread id using posix api | i have a requirment that i have to get thread name from thread id or if that is not possible how to get thread name. Here i am not creating the thread. I am creating the library and this library is used by application and library code will be running in application thread context, i want to print thread name in console... | As far as I know, posix threads don't have names, but you might use TLS to store a name. See here for an example (not with strings).
|
5,080,286 | 5,080,363 | How to properly use namespaces to avoid name collision? | I'm a bit confused concerning proper usage of C++ namespaces. It is clear for me how they can help to avoid conflicts (name collision), but it is not clear anymore when it comes to the using keyword. I mean, suppose I have a part of my code that I put into a namespace, and create a class, say
namespace my
{
class v... |
Of course, when I use it, I wouldn't like to type my::vector all the time, so I'd like using namespace my. However, I could eventually need something from the std namespace, and then I want using namespace std at the same time, but this will bring me back to the initial name collision problem.
Yes, it would bring you... |
5,080,456 | 5,080,607 | How is it possible to have a buffer overrun on one platform but not another? | I'm hesitant to ask this question because of the vagueness of the situation, but I'd like to understand how this is possible. I have a C++ application developed using Visual Studio 2008. When I compile the application on Windows 7 64-bit (or Vista 32-bit), the application runs fine. When I compile the application on 32... | Write code so you don't have buffer overruns and you won't have this problem on any platform. Namely, make sure you check the bounds for the buffer you are accessing to make sure you aren't trying to read/write outside of the proper bounds.
|
5,080,517 | 5,080,974 | Audio timescale-pitch modification - Open source examples? | Is anyone aware of any open source libraries/implementations of real-time timescale-pitch modification algorithms?
| Scaletempo might do what you want. MPlayer uses it.
|
5,080,735 | 5,080,881 | Indri Lemur: issue with the make file | I want to compile my indri lemur application, so i've created a folder with myapp.cpp and copied Makefile.app.in from the indri root directory to myApp/Makefile.app as explained here: Write your own app
However when I run make, I get the following errors. Is this an error specific to the toolkit or is about the compile... | The link states that you should copy Makefile.app, not Makefile.app.in.
You need (usually) a configure-script to build ordinary Makefiles from .in files.
|
5,080,848 | 5,080,980 | Disable GCC "may be used uninitialized" on a particular variable | I'm getting this warning on a stack variable:
warning: object.member may be used uninitialized in this function
In this case I do not wish to force initialization to just to get rid of the warning as it consumes CPU cycles. The variable is a POD structure so a memset on it is not zero cost. I can verify that the varia... | Try doing this:
#pragma GCC diagnostic ignored "-Wuninitialized"
foo(b); /* no diagnostic for this one */
This pragma comes in three interesting and helpful flavors : warning, error, ignored. See 6.56.10 Diagnostic Pragmas for their usages. The link says,
GCC allows the user to selectively
enable o... |
5,081,123 | 5,081,272 | How to add code at the entry of every function? | I want to add some code before every function call to do some checking. The only way I know is:
#define SOME_CODE printf("doing something...");
class testObject
{
void function1()
{
SOME_CODE
...
}
void function2()
{
SOME_CODE
...
}
}
Is there a cleaner way to achieve this? I'm looking for a method so I don't hav... | Depending on what you're hoping to achieve as a result of this you can sort of make something (easily enough for free functions or static member functions) in C++ with functor objects which wrap real calls, e.g.:
#include <iostream>
template<void f(void)>
struct Wrap {
void operator()() const {
std::cout << "... |
5,081,143 | 5,082,127 | Reader Writer Lock supporting low priority writers | I am trying to find (or implement) a Reader/Writer Lock which supports low-priority writers, but have been unsuccessful in researching any existing solutions.
What I mean by low-priority writer is: "will yield its place in line" to incoming readers or normal writers.
Certainly will lead to starvation if there is a cons... | I don't know anything 100% like your proposal, but there's some existing interfaces that are close:
Many existing r/w lock APIs have a "try lock" interface, like pthread_rwlock_trywrlock() on UN*X systems. These are wait-free and will only acquire the lock if noone owns it nor waits for it already.
You'd normally use t... |
5,081,181 | 7,165,023 | htmlcxx c++ crawling html | I've read many different issues from different people regarding libraries to crawl HTML. I've decided to go with htmlcxx, because it looks simple and it's in the Ubuntu repository.. Anyhow, while playing with htmlcxx I was trying to achieve a simple task and grabbing the text between heading tags. Using the iterator, i... | You can add this method to Node.h to get the contents contained between the tags (passing the original html string as an argument):
inline unsigned int contentLength() const { this->mLength - this->mText.length() - this->mClosingText.length(); }
inline std::string content(const std::string& html) const { return html.su... |
5,081,245 | 5,081,671 | mfc program using wrong decimal separator/language | I have the comma as the decimal separator in my Windows regional settings (Portuguese language), and all the programs I develop use the comma when formatting strings or using atof.
However, this particular program that came into my hands insists on using the dot as the decimal separator, regardless of my regional setti... | I'm not calling setlocale anywhere in the program or any other language changing function AFAIK.
That'd be why. C and C++ default to the "C" locale. Try setting the locale to "": setlocale(LC_ALL,"");
|
5,081,368 | 5,081,472 | CPP compile error: included files not found | In my app.cpp file I have the following line: #include "indri/Repository.hpp"
However when I run make (makefile below): I get the following error:
indri/Repository.hpp:22:32: error: indri/Parameters.hpp: No such file or directory
The reason is that the Repository.hpp includes other hpp in the same folder but it uses "... | Did you forget to add the current directory?
## your application name here
APP=myapp
SRC=$(APP).cpp
## extra object files for your app here
OBJ=
prefix = /usr/local
exec_prefix = ${prefix}
libdir = ${exec_prefix}/lib
includedir = ${prefix}/include
INCPATH=-I$(includedir) -I. # can you spot the difference?
LIBPATH=-L$... |
5,081,678 | 5,090,236 | Handling default parameters in cython | I am wrapping some c++ code using cython, and I am not sure what is the best best way to deal with parameters with default values.
In my c++ code I have function for which the parameters have default values. I would like to wrap these in such a way that these default values get used if the parameters are not given. I... | You could declare the function with different parameters ("cppcode.pxd"):
cdef extern from "cppcode.hpp":
int init(char *address, int port, bint en_msg, int error)
int init(char *address, int port, bint en_msg)
int init(char *address, int port)
int init(char *address)
int init()
Where "cppcode... |
5,081,794 | 5,081,869 | How can I store a reference to `std::cout` as a class member | I'm using a class meant to be used like this:
Output() << "Hello.\n";
In its operator<< I explicitely use std::cout, but I'd like to have a static class member that resolves to `std::cout´ so I can do stuff like this:
copy(some_string_set.begin(), some_string_set.end(), ostream_iterator<string>(Output::m_stream, ", ")... | struct Output
{
static ostream& stream;
};
ostream& Output::stream = cout;
int main()
{
Output::stream << "hey";
}
Works fine here.
|
5,081,904 | 5,084,042 | GetWindowLongPtr fails returning Retrieves the user data | I created win32 wrapper before but I lost the files... So I'm gonna creating them again. The problem is with my router(static window processor).
Here is my code
CFramework *wnd = 0;
// retrieve associated Window instance
wnd = reinterpret_cast<CFramework *>(::GetWindowLongPtr(hWnd, GWL_USERDATA));
// call the wi... | Your window may receive some messages before WM_CREATE. I did something like this a while ago, and there were sizing and positioning messages, along with WM_NCCREATE, that arrived before the WM_CREATE. So you shouldn't expect to see the value there on those messages.
Are you compiling for 32-bit or 64-bit? If 64-bit... |
5,082,224 | 5,082,335 | static constant referencing to parent variable | Lets say you want to use the same memory that a parent class does but would like a more fitting name for its new function. This is achieved like this (for example SOCKADDR from winsock):
class Parent{
int a;
};
#define myA a;
class Child: public Parent{
void print(){
cout<<myA;
}
};
Much like sta... | One possibility would be:
class Child: public Parent
{
int& myA() { return a; }
void print()
{
cout << myA();
}
void DoSomethingElse()
{
myA() = 10;
}
};
|
5,082,517 | 5,082,975 | computing permutation of specific bits in a number | As part of my master thesis, I get a number (e.g. 5 bits) with 2 significant bits (2nd and 4th). This means for example x1x0x, where $x \in {0,1}$ (x could be 0 or 1) and 1,0 are bits with fixed values.
My first task is to compute all the combinations of the above given number , 2^3 = 8. This is called S_1 group.
Then ... | #include <vector>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
string format = "x1x0x";
unsigned int sigBits = 0;
unsigned int sigMask = 0;
unsigned int numSigBits = 0;
for (unsigned int i = 0; i < format.length(); ++i)
{
sigBits <<= 1;
sigMask <<= ... |
5,082,605 | 5,082,707 | boost & asio as part in big project with Cmake | I want to use Boost core libraries (like lambda) and Boost ASIO library in a large cross-platform project built with the Cmake. I want to put Boost & ASIO in my source control tree and build it as part of project with the Cmake. So I don't want to "install" it on computers and link with it.
How can this be done? Does t... | Both Boost.Lambda and Boost.ASIO are header-only libraries, so in your CMakeLists.txt file, you could include your Boost include directory in the INCLUDE_DIRECTORIES variable, and when your code is built, the header code will be built into your resulting modules.
For situations where you are using non-header-only libra... |
5,082,680 | 5,082,710 | when should I use the new operator in C++ | Say I have a class called Money which has parameters Dollars and Cents
I could initialize it in the followings 2 ways:
Money a(3,15);
Money *b=new Money(3,15);
My question is when should I use (1) and when should I use (2)
| The first one creates a Money object on the stack, its lifespan is within the scope of when it was created. Meaning when you hit a } it goes out of scope and the memory is returned. Use this when you want to create an object within one function.
The second one creates a Money object on the heap, its lifespan is as long... |
5,082,871 | 5,083,193 | Searching for occurrence of a string using c++ | I need to find an occurrence of string in an string. Is there any find function in c++? For example, if I have a string example/example/example/a/a, how to get a number of occurrences of string example, which in this case is 3?
| Use the substring function.
std::string to_search = "example/example/example/a/a";
std::string to_find = "example";
int count = 0;
for (int i = 0; i < to_search.length() - to_find.length(); i++) {
if (to_search.substr(i, to_find.length()) == to_find)
count++;
}
|
5,083,032 | 5,083,203 | How to UTF-8 encode a character/string | I am using a Twitter API library to post a status to Twitter. Twitter requires that the post be UTF-8 encoded. The library contains a function that URL encodes a standard string, which works perfectly for all special characters such as !@#$%^&*() but is the incorrect encoding for accented characters (and other UTF-8).
... | If you have a wide character string, you can encode it in UTF8 with the standard wcstombs() function. If you have it in some other encoding (e.g. Latin-1) you will have to decode it to a wide string first.
Edit: ... but wcstombs() depends on your locale settings, and it looks like you can't select a UTF8 locale on Wind... |
5,083,047 | 5,088,954 | linker problem with libstdc++.so.6 in connection with cuda | today i encountered a problem with linking my compiled cuda stuff.
i have a uptodate debian testing w/ 2.6.32-3-amd64.
i worked all day on my code. compiling from time to time.
had no problem. but then after a minor code change i got following error:
gcc -o pa CUDA.o histogram256.o histogram64.o main.o -lrt -lm -l... | adding
-L/usr/lib64 -lstdc++
to my makefile/commandlineparameters fixed it.
|
5,083,198 | 5,087,444 | Yacc expansion of optional clause using the same keyword as following clause | I'm developing a small DSL and having problems getting Yacc (Bison) to cleanly parse for the following symbols:
START (RETURN expression WHERE expression)* RETURN (expression)?
This is what I have so far, but I keep getting shift / reduce conflicts and I'm not sure how to fix them:
start: START conditional_returns ret... | By themselves, the above rules don't cause any problems; yacc/bison can handle them just fine with no shift/reduce or reduce/reduce conflicts. Where you might be getting into problems is if start is also a legal expression. If that's the case, the language is ambiguous -- when you have a start within a start, a WHERE... |
5,083,390 | 5,083,426 | What is wrong with precompiled headers and ASLR? | I read it on several sites that precompiled headers and address space layout randomization is incompatible. What makes them incompatible? What would it take to fix it?
My question is OS independent I heard this is a problem on linux with grsecurity and on newer windows versions. (And I don't know what else has ASLR.)
| Precompiled headers are not incompatible with ASLR.
The particular technique used to implement precompiled headers that was used by older versions of the Visual C++ compiler was broken by ASLR. There is an article on the Visual C++ Team Blog with details on the problem and an explanation of how it was fixed. There ... |
5,083,485 | 5,083,808 | Multiple threads and blocking sockets | I'm writing a TCP server on Windows Server 2k8. This servers receives data, parses it and then sinks it on a database. I'm doing now some tests but the results surprises me.
The application is written in C++ and uses, directly, Winsocks and the Windows API. It creates a thread for each client connection. For each clien... | If your lines are ~120–150 characters long, you are actually saturating the network!
There's no issue with sockets. Simply transfering 3 times 100k lines, 150 bytes each, over a 100 Mbps line (1 take 10 bytes/byte to account for headers) will take... 4.5 s! There is no problem with sockets, blocking or otherwise. You'v... |
5,083,612 | 5,083,735 | Why doesn't my simple XOR encryption program translate the characters right, and why does it add more characters at the end? | I'm making a XOR based en/decryptor, that works like this.
You have a plaintext character, for example 3, and a user key, for example 5.
Written in bits:
3 = 00000011
5 = 00000101
Now if we do XOR operation, we get 6:
6 = 00000110
This can be reversed by saying 6 XOR 5, which is 3.
So I have made this program. But i... | From the looks of things, the encryption has almost nothing to do with anything (or at least with the problem) here.
while(!fin.eof() && znak != ' ')
A loop of the form while (!whatever.eof()) is pretty much guaranteed to work incorrectly.
fin.get(buffer, sizeof(buffer));
When you do this, note that it does not ... |
5,083,851 | 5,084,398 | Can't Compile using Qt Creator on Windows 7 x64 | Using a fresh install of Qt Creator, I am unable to compile anything including any of the demo projects, or any of my own. I installed Qt Creator on a fresh install of XP on VMWare and it works and compiles fine. My computer is running Windows 7 x64. When attempting to build one of the demo projects, there are several ... | You may have some mis-configuration in the Qt4 preferences panel. Go to Tools > Options and select Qt4 in the side bar. Select your Qt installation and make sure the MinGW directory points to a valid mingw installation.
|
5,083,998 | 5,084,030 | Efficency of repeated arithmetic between two macros | In an ANSI C project I am working on, I have two macros defined: PERIOD_IN_MS and CYCLES_PER_MS. In the actual period handling logic, I do many comparisons between a counter that is incremented every ''cycle'' and PERIOD_IN_MS * CYCLES_PER_MS. I'm concerned that this arithmetic operation is repeatedly evaluated during ... | The standard doesn't impose any requirement to do this, but any sensible compiler will fold these constants down into one at compile-time. See e.g. http://en.wikipedia.org/wiki/Constant_propagation.
If you're curious to know whether this has actually happened, you can always take a look at the assembler generated by t... |
5,084,209 | 5,084,260 | Check if template argument is inherited from class | I want to check if the type given to a template is inherited from a base class in my project.
It should work like one would expect it from the following example:
template< class T : public CBaseClass >
Is it possible to do this with templates, if not, how else can I do it?
| You can use boost::is_base_and_derived from Boost, combined with BOOST_STATIC_ASSERT. If you are using a compiler with TR1 or C++0x support, there are equivalents of those constructs in the standard library (std::is_base_of, and the static_assert statement in C++0x).
|
5,084,542 | 5,084,620 | Forcing enum to be of unsigned long type | Is it possible to force the underlying type of an enumeration to be unsigned long type? Thanks
| In C++11 and higher, you can explicitly mention what type you want:
enum MyEnumeration: unsigned long {
/* ... values go here ... */
};
This will allow you to explicitly control the underlying type.
In C++03, there is no way to force an enumerated type to have any particular underlying implementation. Quoth the C+... |
5,084,734 | 5,085,744 | #import lead to a HRESULT 0x80040154 "Not registered class" | I'm trying to use a COM DLL from VC++ 2005. I created a TestCOMlib.dll with ATL, created a simple interface ISimple and added one property (type LONG, name Property01) and one method (name Method01).
The DLL seems to be correctly registered in the system (I use OleView to check the entries).
I created a simple MFC dial... | The underlying class for these smart COM pointers is _com_ptr_t. You are trying to use this constructor:
// Constructs a smart pointer given the CLSID of a coclass. This
// function calls CoCreateInstance, by the member function
// CreateInstance, to create a new COM object and then queries for
// this smart pointe... |
5,085,091 | 5,085,285 | Binary Search Tree Implementation in C++ STL? | Do you know, please, if C++ STL contains a Binary Search Tree (BST) implementation, or if I should construct my own BST object?
In case STL conains no implementation of BST, are there any libraries available?
My goal is to be able to find the desired record as quickly as possible: I have a list of records (it should no... | What you need is a way to look up some data given a key. With the key being an unsigned int, this gives you several possibilities. Of course, you could use a std::map:
typedef std::map<unsigned int, record_t> my_records;
However, there's other possibilities as well. For example, it's quite likely that a hash map woul... |
5,085,141 | 5,085,720 | Selecting an icon from an image grid | I have a grid of icons and I want to select an individual icon and save it in separate image file. The image doesn't need to be processed further just simply split apart. Any thoughts on how to let the computer do this work for me?
| For Windows, Bitmap::Clone will do it for you. MSDN Link
|
5,085,162 | 5,086,296 | Bad File Descriptor error when setting non-blocking on a boost::asio::ip::tcp::socket | I'm new to boost and I've been trying out boost::asio. The problem is I always get an "Bad File Descriptor" error/exception when setting some options (I need to make it non-blocking). Even this here fails:
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main( )
{
boost::asio::io_service io_service;
tcp... | You invoked the socket constructor that does not open the socket. You could use one of the other overloads that open the socket prior to invoking socket::io_control(), or open the socket explicitly.
boost::asio::ip::tcp::socket socket(io_service);
socket.open(boost::asio::ip::tcp::v4());
|
5,085,231 | 5,085,323 | C++: select argmax over vector of classes w.r.t. arbitrary expression | I have trouble describing my problem so I'll give an example:
I have a class description that has a couple of variables in it, for example:
class A{
float a, b, c, d;
}
Now, I maintain a vector<A> that contains many of these classes. What I need to do very very often is to find the object inside this vector that sat... | template <typename F>
struct CompareBy
{
bool operator()(const typename F::argument_type& x,
const typename F::argument_type& y)
{ return f(x) < f(y); }
CompareBy(const F& f) : f(f) {}
private:
F f;
};
template <typename T, typename U>
struct Member : std::unary_function<U, T>
{... |
5,085,261 | 5,085,309 | Why is my program printing out the null termination character? | When I run this, it will SOMETIMES print out a null termination character. Most of the time it will, and probably 1/5 times it will print just the characters.
void cryptogram::Encrypt(){
cout<<"encrypt"<<endl;
char Alphabet[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
fin.open("original.txt");
cout<<"file opened";
if(... | You are iterating a from 0 to 26 (inclusive) but Alphabet contains only 26 elements, so you sometimes read beyond the array boundary. This can result in a NULL character or anything else that is stored in this memory location. You should limit your for-loop to <=25 or <26
|
5,085,322 | 5,088,240 | cairo + openGL + Glut + VS 2010 + Windows 7 | I'm pretty dump :) So could anybody help and write step-by-step manual, how to install "cairo", "glut" and use it in VS 2010 project (C++) on Windows 7?
PS: the most fun thing that i managed to do that without any problem in Linux.
| I don't know cairo, but setting up GLUT is rather straightforward.
Download FreeGLUT
Unpack the downloaded archive
Go the directory unpack-dir/freeglut-x.x.x/VisualStudio2008
Open the visual studio project
Rebuild the project for each target (release, debug) you want to create
This should create a DLL file and a lib ... |
5,085,392 | 5,085,425 | What is the value of an undefined constant used in #if? | My preprocessor appears to assume that undefined constants are 0 for the purpose of evaluating #if conditions.
Can this be relied upon, or do undefined constants give undefined behaviour?
| Yes, it can be relied upon. The C99 standard specifies at §6.10.1 ¶3:
After all replacements due to macro expansion and the defined unary
operator have been performed, all remaining identifiers are replaced with the pp-number
0
Edit
Sorry, I thought it was a C question; still, no big deal, the equivalent section... |
5,085,533 | 5,085,588 | Is a C++ preprocessor identical to a C preprocessor? | I am wondering how different the preprocessors for C++ and C are.
The reason for the question is this question on a preprocessor-specific question where the paragraph of the standard that addresses the question has a different wording (and a different paragraph number) and also are difference concerning the true and fa... | The C++03 preprocessor is (at least intended to be) similar to the C preprocessor before C99. Although the wording and paragraph numbers are slightly different, the only technical differences I'm aware of between the two are that the C++ preprocessor handles digraphs (two-letter alternative tokens) and universal charac... |
5,085,796 | 5,085,834 | Qt: How to create windows DLL (that exports functions)? | I need to create a windows DLL that exports functions and has a graphical user interface. The reason for the GUI in the DLL is that the DLL serves as a kind of plugin for another 3rd party application. Currently I only have access to Visual Studio Express which AFAIK doesn't support MFC so I'm looking for alternative... | Add the folowing line to the .pro file: TEMPLATE = lib
That's just about all you'll have to do to have QtCreator make your 'app' into a dll.
|
5,085,915 | 5,086,014 | What is the best hash function for uint64_t keys ranging from 0 to its max value? | Assuming that we have a set of elements and want to store them in a hash map (for example std::unordered_set), and each element has a key of type uint64_t whose value can vary from 0 to its maximum possible value, is it the best choice to use trivial hash function, where a hash value of a key is the key itself? Does it... | If all you have to hash is a uint64_t of any possible value with unknown probabilities, and your output must be a uint64_t, then you don't gain any advantage by changing the value. Just use the key itself.
If you knew something about the distribution of your values or your values were restricted to a smaller range (wh... |
5,086,103 | 5,086,127 | gcc stack optimization | Hi I have a question on possible stack optimization by gcc (or g++)..
Sample code under FreeBSD (does UNIX variance matter here?):
void main() {
char bing[100];
..
string buffer = ....;
..
}
What I found in gdb for a coredump of this program is that the address
of bing is actually lower than that buffer (n... | Compilers are free to organise stack frames (assuming they even use stacks) any way they wish.
They may do it for alignment reasons, or for performance reasons, or for no reason at all. You would be unwise to assume any specific order.
If you hadn't invoked undefined behavior by overflowing the buffer, you probably nev... |
5,086,604 | 5,086,654 | C++ Reflection Guide/Tutorials | I am finding it difficult to find anyway to implement Reflection in C++. I have only seen examples from AGM::LibReflection and Game Programming Gems 5. Does anyone know of a tutorial or decent code sample for how to do this?
So far I know of Boost/QT's built in system, but I am not looking to use theirs (please do not ... | Reflection is rotten way to inspect properties of a program. You can only "reflect" what the guy designing the compiler wired into the reflection machinery. That's usually not a lot (what reflection system do you know that will let you peer inside an expression?) and it depends on the language. And for something lik... |
5,086,896 | 5,086,966 | C++ Different constant member in each derived class, how to move function to remove duplication in access? | I have derived classes that differ in some constant attribute. In all derived classes, I have a function that returns attribute. Is there a way to move the get_x function into the base class to remove the duplication? I have looked in this thread and a lot of google searches but I couldn't find exactly what I want:
... | A bit kludgy, but you could potentially use something similar to the following to do this:
template <attribute x> class Base
{
public:
attribute get_x ( ) { return x; }
};
class Derived1 : public Base<SOME_ATTRIBUTE_1>
{
...
};
class Derived2 : public Base<SOME_ATTRIBUTE_2>
{
...
};
Similar to Ka... |
5,086,928 | 5,086,983 | the equivalent of sscanf_s in C#? | UnlockOffset is DWORD. thisKey is a char[5]
if(EOF == sscanf_s(thisKey, "%d", &UnlockOffset))
How would the above code be done in c# ?
DWORD was converted to UInt32 and thiskey remained char array but I still dont understand the sscanf_s.
PS: I did check MSDN but was not able to understand it very well which was why I... | sscanf_s basically reads a string and extracts stuff that matches the format string. It'll return EOF if it couldn't extract stuff to match all the format thingies.
You could do something like
string str = new string(thisKey);
if (!UInt32.TryParse(str, out UnlockOffset))
which would accomplish something similar, but ... |
5,086,937 | 5,086,946 | How to get the windows time in vc++? | I am trying to find out how to get the date (day of week; day of month with 1st, 2nd, etc; month; and year). In Microsoft Visual C++ 2010 Express, the underlined section of the following code gets the error:
int tm::tm wday
Error: a nonstatic member reference must be relative to a specific oject
#include <iostream>
#in... | tm is a struct. You need to create an object to access it's member.
See http://www.cplusplus.com/reference/clibrary/ctime/localtime/ for an example
|
5,086,999 | 5,087,102 | How to copy a file to a dynamic string array | I'm trying to read in an entire input file into a string. Right now I have:
bool DynString::readLine(std::istream& in)
{
if(in.eof())
{
*this = DynString(); // Default string value.
return(false);
}
char s[1001];
in.getline(s, 1001);
// Delete old string-value and create ne... | Why not something simpler like the following or do you have to use your DynString class?
static std::string readFile(const std::string& sFile)
{
// open file with appropriate flags
std::ifstream in1(sFile.c_str(), std::ios_base::in | std::ios_base::binary);
if (in1.is_open())
{
// get length of file:
in... |
5,087,091 | 5,087,106 | What does the STL map[key] return if the key wasn't a initialized key in the map? | Here is some example code:
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
map<char, string> myMap;
myMap['a'] = "ahh!!";
cout << myMap['a'] << endl << myMap['b'] << endl;
return 0;
}
In this case i am wondering what does myMap['b'] return?
| A default constructed std::string ins inserted into the std::map with key 'b' and a reference to that is returned.
It is often useful to consult the documentation, which defines the behavior of operator[] as:
Returns a reference to the object that is associated with a particular key. If the map does not already contai... |
5,087,364 | 5,098,057 | How to query a constexpr std::tuple at compile time? | In C++0x, one can create a constexpr std::tuple, e.g. like
#include <tuple>
constexpr int i = 10;
constexpr float f = 2.4f;
constexpr double d = -10.4;
constexpr std::tuple<int, float, double> tup(i, f, d);
One also can query a std::tuple at runtime, e.g. via
int i2 = std::get<0>(tup);
But it is not possible to query... | std::get is not marked constexpr, so you cannot use it to retrieve the values from a tuple in a constexpr context, even if that tuple is itself constexpr.
Unfortunately, the implementation of std::tuple is opaque, so you cannot write your own accessors either.
|
5,087,417 | 5,087,489 | QDockWidget Tab Position | When I group multiple QDockWidgets in the same place, their tabs go at the bottom. Is there a way to put them at the top?
Even better is if I can replace the title bar with the tabs themselves. the Eclipse IDE has very similar behavior, as can be seen in this screenshot:
.
For example, the JUnit tab is also it's head... | You can control where the tabs are in each of the dock areas with QMainWindow::setTabPosition.
|
5,087,518 | 5,100,813 | how to pause and resume wxThread with button event | I am trying to fill wxListCtrl with the database, and for this I'm using wxThread concept. I want to add two buttons in the frame, for pause and resume thread. How can this possible?
| Finally, I got the solution - I was trying to pause and resume thread with the button event. For this
Take two buttons wxButton *stop, *resume
Create two button events:
void onstopbuttonclick(wxCommandEvent & event);
void onresumebuttonclick(wxCommandEvent & event);
At stop button event, write:
void login::onstopbutt... |
5,087,587 | 5,087,621 | Operator Overloading with Templates inside of a BST | I currently have a binary search tree setup, utilizing templates to allow me to easily change the type of data within the binary search tree. At the moment, I'm having trouble overloading the studentRecord class which contains the data to be stored in the tree. I need to overload the comparison operators within this cl... | Your tree is a tree of pointers. So when you try to insert an element into the tree the values of the pointers is compared. So your overloaded operator is not called. If you want to use the overloaded operator then you should create bst<studentrecord>
|
5,088,133 | 5,088,147 | Error for pointer to member in C++ | Header file
#include <iostream>
#include <cstring>
const unsigned MaxLength = 11;
class Phone {
public:
Phone(const char *phone) {
setPhone(phone);
}
void setPhone(const char Phone[ ]);
const char* getPhone();
private:
char phone[MaxLength+1];
};
Cpp file
#include "Phone.h"
#include... | You are missing a pair of parentheses after getPhone in if (checkNum(i1.getPhone)); it should be if (checkNum(i1.getPhone())).
|
5,088,392 | 5,088,510 | Is there any function called after the OnInitDialog function in MFC? | I want to create a thread after the creation of a dialog box in MFC. Is there any function that Windows has provided and is automatically called after OnInitDialog so that I can create my thread inside it?
| You can simply create your thread in the OnInitDialog function. There's no reason to overcomplicate things by going and searching for a different function, or splitting your initialization code up in two pieces. (There also isn't any such function, because there's no corresponding Windows message that is sent.)
If you ... |
5,088,398 | 5,095,825 | Using git for VS2010 project: Can't add file *.opensdf | I'm using git to track a C++ project in VS2010. I'm using ignore patterns found on stackoverflow, which usually do not exclude the *.opensdf file. Unfortunately, when trying to commit the file, I get the following error:
error: open("foo.opensdf"): Permission denied
error: unable to index file foo.opensdf
fatal: addi... | *.opensdf is a temporary file opened only while .vcxproj/.sln is loaded to Visual Studio IDE. It should be added to your .gitignore file.
See the accepted answer on this question: What should be contained in a global source code control ignore pattern for Visual Studio 2010?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.