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
3,914,594
3,914,937
Webcam: Programmatically adjust Webcam parameters
In our project, we would like to access the webcam image programmatically. The main problem we have is that the webcam automatically adjusts the sensitivity depending on the brightness of the captured image. Is there any (platform-independent) way to change this kind of parameters for the webcam (preferably any model)?...
There most likely won't be any platform independent way to do what you need. If there is, it's probably by using some high level language, which likely won't suit. I don't know about the linux platform, but I'm a C++/windows/COM/DirectShow developer who works on internet based video applications. On the Windows platfo...
3,914,633
3,914,664
mem_fun_ref question
Why is this code resulting in a compiler error? #include <iostream> #include <algorithm> using namespace std; class X { public: void Print(int x) { cout << x << endl; } }; int main() { X x; mem_fun_ref<void, X, int>(&X::Print) p; }; Error main.cpp:18: error: expected ...
mem_fun_ref is a function template, so it does not name a type. mem_fun_ref<void, X, int>(&X::Print) is a function call that returns a value, so it makes no sense that there is a p following it. The return value of that function call is a mem_fun1_ref_t<void, X, int>, in case you were looking for that.
3,915,113
3,948,150
Standard library tags
I use tag files for code completion and for a quick, inline view of parameters, overloads, files (where declared), etc. Where can I find freely available tags for the C99, C++03, and C++0x standard libraries? (C89 would be better than nothing, but I'd rather have C99.) I prefer tags without cruft; e.g. implementation...
For those exact requirements you will probably have to create those yourself :(
3,915,234
3,915,376
How can this be implemented(elegantly) without using RTTI?
I was coding this up in C# and the quickest solution to come to mind used the "as" or "is" keywords. I began wondering how I could implement it neatly in C++(without RTTI)... or even in C# without the aforementioned keywords. Here is the problem (simplified): There is a class Command which contains a stream of so calle...
You could also try using the Visitor Pattern. Though it's probably overkill for your simple scenario.
3,915,269
3,915,374
Why doesn't the assembly seem consistent to me?
Dumped from visual studio: CheckPointer(pReceivePin,E_POINTER); 017D616D cmp dword ptr [ebp+0Ch],0 017D6171 jne CBasePin::Connect+4Dh (17D617Dh) 017D6173 mov eax,80004003h 017D6178 jmp CBasePin::Connect+1A7h (17D62D7h) But the actual definition is: #define CheckPointer(p,ret...
You've left out enough that it's hard to be sure, but the part that can be sorted out looks reasonable. NULL == 0, so: 017D616D cmp dword ptr [ebp+0Ch],0 ; if [ebp+0ch] == 0 017D6171 jne CBasePin::Connect+4Dh (17D617Dh) ; goto 172617dh 017D6173 mov eax,80004003h ...
3,915,288
3,915,642
Marshalling a C# Dictionary over COM interop to C++
Is there a good way of marshalling a Dictionary<string, string> over COM interop? Ideas so far include tokenising each KeyPair to an array of strings which can be marshalled as a SafeArray, or having two string arrays containing keys and values. Neither seems particularly satisfactory. Any ideas?
I doubt you will find a very elegant solution, since COM interop with non-trivial managed types is always going to involve custom code. Since your recipient COM client has to know the semantics of the data, you could just marshal to a single SafeArray whose entries are Key1, Value1, Key2, Value2, and so on. Maybe that'...
3,915,379
3,915,632
What's such macro for?
#define ValidateReadPtr(p,cb) 0 I can't think of a use case for this kind of macro,what about you?
I can only find the ValidateReadPtr() macro in the wxdebug.h header for the Windows Mobile SDK (even though MSDN indicates it's part of the DirectShow APIs). In wxdebug.h it's defined as: #define ValidateReadPtr(p,cb) \ {if(IsBadReadPtr((PVOID)p,cb) == TRUE) \ DbgBreak("Invalid read pointer");} I suspect t...
3,915,392
3,915,759
Find the number in an array which occurred most number of times
Given an integer array, i need to find which number occurred most number of times. I have written algorithm as below. Use a map to store number and number of times it occurred. map<int, int> Key: represents the number value: represents number of times key occurred. Scan input array and update the map with number an...
Your algorithm is pretty good. It's actually O(N Log N), because of the N std::map (a tree based map) insertions you're doing (Log N each). This dominates the time complexity of the algorithm, as the second phase is linear. An improvement would be to use a hash map, giving you a linear algorithm overall.
3,915,410
3,915,507
How to convert sRGB to CIELAb and CIELab to sRGB efficiently?
I don't understand how to convert sRGB to CIELab and backward. Help me please. it's desirable in с++ code
Convert from sRGB to RGB by applying inverse gamma, convert RGB to XYZ using 3x3 matrix, convert XYZ to Lab using standard formula and D6500 white point References: Lab http://en.wikipedia.org/wiki/Lab_color_space sRBG http://en.wikipedia.org/wiki/SRGB_color_space The rest... you can do on your own :-)
3,915,511
3,915,584
How do breakpoints work in C++ code?
How do breakpoints work in C++ code? Are they special instructions inserted in between some assembler instructions when the code is compiled? Or is there something else in place? Also, how are stepping-through-the-code implemented? The same way as breakpoints...?
This is heavly depend on the CPU and debugger. For example, one of the possible solution on x86 CPU: Insert one-byte INT3 instruction on the required place Wait until breakpoint exception hits Compare exception address to the list of breakpoint to determine which one Do breakpoint actions Replace INT3 with original by...
3,915,594
3,915,647
Template parameters in C++
Suppose I have arbitrary template method, which could receive parameters by value and by const reference (obviously, for trivial types and for objects accordingly). How is this situation handled when writing template function prototypes? I could make something like: template <typename T> void Foo(T value) { // Do so...
Just take by const reference ALWAYS, because there isn't much overhead in passing primitive types as const references.
3,915,717
3,915,825
Decode C++ encoded ASCII extended values?
I have a little question regarding ASCII Codes. Is it possible to to find out what type of encoding is used in C++ for ASCII extended values? I want to try and find a way to decode a game animation source file without having to de-compile the game source which is not allowed. I simply want to understand whats going on ...
The code you see is Binary. i'm not sure what you are trying to do, but basically you need to know the file format before you can do any changes and most chances are it's not plain text nor UTF-8 based file but binary, file in a format decided by the application's author. You can try to either look for the .pme extensi...
3,915,758
3,915,794
Specifying a templatized class with traits
I have a struct which indicates a trait: template<typename T> struct FooTraits { static const NEbool s_implementsFoo = false; }; And I can specialize it with a class, thus: class Apple {}; template<> struct FooTraits< Apple > { static const NEbool s_implementsFoo = true; }; However currently I cannot use Foo...
Originally I wrote, the FooTraits doesn't depend on the templated argument so why put in a template before I realized my brain fart. That's the downvote and the comments Can you do this? It's compiling on my machine template<typename T> struct FooTraits< Fruit<T> > { static const NEbool s_implementsFoo = true; };...
3,915,904
3,917,107
Model, View, Controller - I understand the class diagram, but I don't understanding all the threading issues. Advice?
I recently read the Head First Design Patterns book and I especially liked how the chapter on MVC seemed to bring everything together from the previous chapters. However, I am now on the verge of implementing a MVC pattern (using wxWidgets in C++) and I am beginning to realize that I don't understand threading issues ...
MVC was thought up originally for message based systems (Smalltalk), what in a sense is an opposite to multi-threading. Best (theoretical) way known to me how to marry the MVC and multi-threading is the active object (or actor) concept: the object lives in its own threads, can send/receive messages/events to other acti...
3,915,940
3,916,375
C++ void cast and operator comma in a #define
I found this while reading some source code. #define MACRO(x) if((void) 0, (x)); else some_func(); I don't fully understand the reasons behind that operator comma and the void cast. This has probably something to do with macro protection, I know that (void)0 is used sometimes to protect cascading elses in macros suc...
I would guess that the trick is used to prevent the user from declaring variables in the if condition. As you probably know, in C++ it is legal to do this if (int i = some_func()) { // you can use `i` here } else { // and you can use `i` here } The use of comma operator in that definition will prevent macro usa...
3,916,097
3,916,147
Integer Byte Swapping in C++
I'm working on a homework assignment for my C++ class. The question I am working on reads as follows: Write a function that takes an unsigned short int (2 bytes) and swaps the bytes. For example, if the x = 258 ( 00000001 00000010 ) after the swap, x will be 513 ( 00000010 00000001 ). Here is my code so far: #include...
New in C++23: The standard library now has a function that provides exactly this facility: #include <iostream> #include <bit> int main() { unsigned short x = 258; x = std::byteswap(x); std::cout << x << endl; } Original Answer: I think you're overcomplicating it, if we assume a short consists of 2 bytes (16 bit...
3,916,133
3,926,582
Simulate key press events for ioquake3 in Mac OSX
I am currently writing an application which simulates key press events in Mac OSX to control ioquake3. My current approach is to create the key press events with the Quartz Event Services. This works fine with e.g. TextEdit but not with ioquake3. CGKeyCode keyCode = 126; // 126 is the "up" key CGEventRef event1 = CGEve...
I solved my problem and everyone who is interested, here is the solution: I will describe a simple example which makes things clear. As mentioned before i use the Quartz Event Services, to generate the key press event. If you want to constantly move the character in ioquake3 forward, you have to constantly produce key ...
3,916,177
3,916,222
Evaluation of C expression
int main() { int i = -3, j = 2, k = 0, m; m = ++i || ++j && ++k; printf("%d %d %d %d\n", i, j, k, m); return 0; } i thought that && has more precedence that || as per this logic ++j should execute, but it never does and the program outputs -2 2 0 1. What is going on here? What are the intermediate steps?
&& does have higher precedence than ||, which means that ++i || ++j && ++k parses as ++i || (++j && ++k). However this does not change the fact that the RHS of || only executes if the LHS returns 0. Precedence does not affect order of evaluation.
3,916,439
3,916,465
Floating point issue in C
Possible Duplicate: strange output in comparision of float with float literal float a = 0.7; if (a < 0.7) ; Why does the expression here evaluate to true?
Floating point numbers have limited precision. 0.7 most likely can't be exactly represented, so the value in a might be 0.6999999999982 or so in a float. This compared to a double 0.7 (which is more precise: 0.6999999999999999999999999384) will show that it is less. Check this out: http://docs.sun.com/source/806-3568/n...
3,916,568
3,917,232
std::find vs. deriving template from vector
I use vectors a lot in my programming, and generally to traverse a vector for an existing value I use std::find as in: std::vector<int> foo; std::vector<int>::iterator pos( std::find( foo.begin(), foo.end(), bar ); This is a real bore. So I went to deriving a template from std::vector to provide a find method: templat...
What about you do what you want to achieve and still not go into the dubious path of inheriting from std::vector define a freestanding function template <typename T> typename std::vector<T>::const_iterator find( const std::vector<T>& v, const T& value ) { return std::find( v.begin(), v.end(), value ); } you can...
3,916,575
3,916,637
ICU Probe All Currency Symbols
Is there a way to probe the ICU library for all UChar's representing currency symbols supported by the library? My current solution is iterating through all locales and for each locale, doing something like this: const DecimalFormatSymbols *formatSymbols = formatter->getDecimalFormatSymbols(); UnicodeString currencySym...
All currency symbols have the category Sc (Symbol, Currency), so you can just enumerate all characters from that category. #include <cstdio> #include <icu/unicode/uchar.h> UBool print_all_currency_symbols(const void* context, UChar32 start, UChar32 limit, UCharCategory type) { if (type == U_CURRENCY_SYMBOL) { ...
3,916,608
3,916,904
How important is standards-compliance?
For a language like C++ the existence of a standard is a must. And good compilers try their best (well, most of the good compilers, at least) to comply. Many compilers have language extensions, some of which are allowed by the standard, some of which are not. Of the latter kind 2 examples: gcc's typeof microsoft's com...
Standards compliance is important for the fundamental reason that it makes your code easier to maintain. This manifests in a number of ways: Porting from one version of a compiler to another. I once had to post a 1.2 million-LOC app from VC6 to VC9. VC6 was notorious for being horribly non-Compliant, even when it w...
3,916,622
3,916,659
C++ For loop loops only 299 times
I'm having this weird problem. My code is simple: #include <iostream> using namespace std; int main() { int num; cout << "number: "; cin >> num; for (int i=0;num>i;i++) { cout << i <<"\n"; } system ("Pause"); return 0; } If the input for example is 1000, the output contains numbe...
Actually it prints all of them, from 0 to 999, but your console's buffer is not large enough. So you see only the last part. if you print into a file, not the console, you'll see :)
3,916,897
3,917,656
wxWidgets and locking resources
I'm new to wxWidgets (C++), and threads for that matter. What should I be aware of concerning shared resources? Should I implement some sort of semaphore-based locking of resources that may be used by both the GUI thread and the worker thread(s)? Does wxWidgets offer some capability for dealing with this?
Not sure what your choice of threading library is at this point but in your case I'd use wxThread (see here & here for documentation). What should I be aware of concerning shared resources? See the Important notes for multithreaded applications part here for wxWidgets specific multi-threading issues. Other than tha...
3,917,085
3,917,209
Is there a C++ cross platform USB library?
I'm (going to be) writing an application in Qt that will run on the 3 main OSes (Windows, Linux and Mac). One of the features of this app is that it needs USB to talk to a piece of custom external hardware. Is there a cross-platform USB library available?
Try libusb. Supported operating systems: Linux, FreeBSD, NetBSD, OpenBSD, Darwin, MacOS X (and Windows, through the libusb-win32 project). But you should note that it uses libusb0.sys kernel-mode driver on Windows, which is not WHQL certified and it could be a problem in 64-bit Windows 7 and Windows Server 2008...
3,917,240
3,917,278
Casting from void* to an object array in c++
I'm having problems getting this to work, class A { public: A(int n) { a = n; } int getA() { return a; } private: int a; }; int main(){ A* a[3]; A* b[3]; for (int i = 0; i < 3; ++i) { a[i] = new A(i + 1); } void * pointer = a; b = (A* [])pointer;...
Arrays are second-class citizen in C (and thus in C++). For example, you can't assign them. And it's hard to pass them to a function without them degrading to a pointer to their first element. A pointer to an array's first element can for most purposes be used like the array - except you cannot use it to get the array'...
3,917,263
3,917,834
Does QWebView/QWebPage download contents in a separate thread or in the main/gui thread?
If it doesn't, then how can I explicitly force it to download asynchronously in a separated thread?
According to the documentation for QWebView::setHtml(): Sets the content of the web view to the specified html. External objects such as stylesheets or images referenced in the HTML document are located relative to baseUrl. The html is loaded immediately; external objects are loaded asynchronously. Same thing goes for...
3,917,927
3,918,030
comparing string literals in c++ templates
I wrote a template function to compare two variables: template <class t> int compare(const t &a, const t &b) { if(a>b) return 1; if (a<b) return -1; return 0; } int main(int argc, const char *argv[]) { cout << compare("hi","world"); return 0; } I get the following error ../src/templates.cpp: In functi...
A string literal of N characters is an array of N constant characters with a terminating '\0' afterwards. So type of "hi" is char const[3] and the one of "world" is char const[6]. So if you pass it to the template, t is deduced to two different types. Note that when in a reference parameter, template argument deductio...
3,917,944
3,917,961
Size of a C++ array in 64 vs 32 bit environment
suppose I have a class defined as follows class foo { char [10] bar; } How would the size of this class differ when in a 64 bit environment compared to a 32 bit one, assuming no padding/packing. I believe the 64 bit version of the class would be 4 more bytes in length since: The class must contain a char* in orde...
No you are not. char [] bar; won't even compile, char bar[10]; is the correct syntax, and no, no pointer is stored, sizeof(char) is always 1 and sizeof bar will be 10, regardless of the architecture. Now for your additional question: You must understand the notion of lvalues and rvalues and lvalue-to-rvalue conversions...
3,917,969
3,918,011
Extending object lifetime
Will fnc like this extend returned object lifetime? If not, are there a ways to do so? const int& f () //<<----Here you see, I'm returning by ref to const int { return 1; }
No, it won't extend the object lifetime. You can't extend the lifetime of the temporary (a temporary is created for binding to the reference), but, you can simply do int f() { return 1; } :-) Cheers & hth., – Alf
3,918,183
3,918,205
Search a variable after its value in debug mode, is it possible?
I am dealing with legacy code and in UI I can find some ID's of my objects which are used at run time. Those id's could help me to find more quickly the portion of code with which I am dealing for that requirement, but I do not know if it is possible to do in debug mode from Visual Studio 2010 (C++ and C#) a search a...
I'm not exactly sure what your asking but Scott Guru's tips and tricks might help you out. http://weblogs.asp.net/scottgu/archive/2010/08/18/debugging-tips-with-visual-studio-2010.aspx
3,918,203
3,918,225
return statement in ternary operator c++
I wrote the absolute function using ternary operator as follows int abs(int a) { a >=0 ? return a : return -a; } I get the following error messages ../src/templates.cpp: In function ‘int abs(int)’: ../src/templates.cpp:4: error: expected primary-expression before ‘return’ ../src/templates.cpp:4: error: expected ‘:’ b...
The second and third arguments to the ternary operator are expressions, not statements. return a is a statement
3,918,344
3,918,561
linear_congruential library in boost
I am trying to use random::linear_congruential in boost (http://www.boost.org/doc/libs/1_33_1/libs/random/random-generators.html#linear_congruential) to generate uniform random numbers. The declaration is defined as: template<class IntType, IntType a, IntType c, IntType m, IntType val> Does anyone know what the last p...
Given seed = 1, the 10,000th value returned by the generator must be val. This is apparently a common practice among PRNG implementors to use the 10,000th value as a test.
3,918,384
3,918,530
declaring the largest array using size_t
i wanted to declare a very large array. i found that the max size of an array is size_t, which is defined as UINT_MAX so i wrote the code like this int arr[UINT_MAX]; when i compile this, it says overflow in array dimension but when i write like this size_t s = UINT_MAX; int arr[s]; it compiles properly. what's the ...
First error: size_t is not necessarily unsigned int, thus its maximum value can be different from the one of unsigned int (UINT_MAX); moreover, in C++ to get informations about the limits of a type you should use std::numeric_limits. #include <limits> size_t s=std::numeric_limits<size_t>::max(); Second error: you won...
3,918,552
3,932,438
background color for certain items(rows) in QFileSystemModel QTreeView
How do i set a custom background color for certain rows in a QFileSystemModel applied on a QTreeView?
you can use setData method and Qt::BackgroundColorRole to achieve that. This should work.
3,918,643
3,918,661
g++ static library depends on dynamic libraries
I have some static library. for example libpuchuu.a it depends on dynamic library. for example libSDL.so (but of cource I have libSDL.a) Creation of libpuchuu.a is simple: ar -rcs object_file_1.o object_file_2.o But I can't link my project with libpuchuu.a! undefined references attack my console! At some forum I have ...
Have you tried adding -lSDL to the command line of your linker? The undefined references are to symbols you are trying to define in lib.cpp which you use ar to package up in libpuchuu.a. Unfortunately, you aren't defining the symbols you think you're defining. using namespace sdl; does not automagically cause everyth...
3,918,811
3,918,881
Copy binary tree in order
The code I wrote so far is: void copyInOrder(TNode *orgTree, Tnode *& copyTree){ if(orgTree !=NULL){ copyInOrder(orgTree->left_link); //create leftmost node of tree but how to link to parent copyInOrder(orgTree->right_link); } } I dont know how to link to the parent to the nodes as its ...
I think it would be something like this. void copyInOrder(TNode *orgTree, Tnode *& copyTree){ if(orgTree !=NULL){ //left side TNode newLeftNode = cloneNode(orgTree->left_link); copyTree->left_link = newLeftNode; copyInOrder(orgTree->left_link, copyTree->left_link); //right s...
3,918,948
3,919,070
is anybody doing anything about 2038 time_t bug?
Possible Duplicate: What should we do to prepare for 2038? I don't mean 'people' in the abstract. I mean are you doing anything and if so what? I am an ancient programmer and recall when I wrote COBOL in the late 70's saying to others in my team "you know - this isn't going to work in 2000". To which the reply was "...
I add a disclaimer to the release notes of my software that says: Best before 2038.
3,919,170
3,919,458
Sinking DWebBrowserEvents2 events appears to hang programmatic navigation
I posted this question on the MSDN forums, but my experience has been a better quality of answer here on Stack Overflow, so I'm posting here as well. As I've posted several times before, I'm working on a browser automation framework, automating Internet Explorer from an external process. My architecture is as follows: ...
Your app is becoming a com server by providing event sinks. The com app needs active 'message pump'(s). If your blocking the message pump while your doing your pipe/dispatch command then it will block IE from calling on your event sink. C# may work simply for the other hidden windows it has and however you have set up...
3,919,194
3,919,325
What is VC++ doing when packing bitfields?
To clarify my question, let's start off with an example program: #include <stdio.h> #pragma pack(push,1) struct cc { unsigned int a : 3; unsigned int b : 16; unsigned int c : 1; unsigned int d : 1; unsigned int e : 1; unsigned int f : 1; unsigned int g : 1; unsigne...
MSVC++ always allocates at least a unit of memory that corresponds to the type you used for your bit-field. You used unsigned int, meaning that a unsigned int is allocated initially, and another unsigned int is allocated when the first one is exhausted. There's no way to force MSVC++ to trim the unused portion of the s...
3,919,221
3,975,094
Compiling QJson statically into Qt Application (multiple declaration errors)
Has anyone had success compiling QJson statically into an application? I am trying to use QJson statically in my Qt application (Windows/Mac), meaning I'm trying to use the source files directly rather than compiling a DLL and using it. Is this possible? My program is producing lots of errors when I attempt to do it, m...
Code that's compiled into a DLL needs to export the functions and classes that it wants to expose to the outside world linking to it at runtime. In this particular case that magic happens in qjson_export.h: #ifndef QJSON_EXPORT_H #define QJSON_EXPORT_H #include <QtCore/qglobal.h> #ifndef QJSON_EXPORT # if defined(QJS...
3,919,311
3,919,323
Is -5 an integer literal?
Is -5 an integer literal? Or is 5 a literal, and -5 is an expression with unary minus taking a literal as an argument? The question arose when I was wondering how to hardcode smallest signed integer values.
It's a unary minus followed by 5 as an integer literal. Yes, that makes it somewhat difficult to represent the smallest possible integer in twos complement.
3,919,412
3,919,428
What's the best way to get started learning how to write an extremely simple multithreaded c++ program that includes mutex and semaphore use?
What package should I use and what would a "hello world"-level program look like?
Try C++: Concurrency in Action Chapter 1. Introduction is freely available in that website, and IIRC that includes a multi-threaded "Hello, World!". C++0x introduces std::thread, the standardized way of using threads in C++, and this book uses that.
3,919,552
3,919,596
GetOpenFileName Program-Defined Directory
I want to create a dialog box that resembles the one created with GetOpenFileDialog. However, I want the dialog to display a list of filenames that the program provides, and these filenames don't necessarily exist as files in a directory. The purpose is to provide a dialog with a similar look and feel for opening files...
No, you'll have to write one yourself. You can however find the common dialog box templates in the PlatformSDK\Include directory; you can use the FileOpen.dlg template to build a dialog similar to the standard Open dialog.
3,919,675
3,919,704
Does g++ still generate an output file even if the program fails to compile/load?
I am compiling some C++ programs through a perl script using: g++ -o out `find ./ -iname "*.h" -or -iname "*.cpp"` This seems to generate an an out file every time, regardless of whether the program compiled successfully or not. Whenever the script tries to run programs like this, it gets permission errors (weird sinc...
The answer to your title's question ("Does g++ still generate an output file even if the program fails to compile/load?") is no: % echo blah > test.cpp % g++ -o out test.cpp test.cpp:1: error: expected constructor, destructor, or type conversion at end of input % ls *out* /bin/ls: *out*: No such file or directory %
3,919,713
3,920,679
Simplest WCF service to be consumed by C++
I'm a complete newbie regarding network stuff, but here are two scenarios I'd like to accomplish: I have a machine running a WCF service Scenario 1: on the same machine, I have a C++ app that needs to get data from that service Scenario 2: on a different machine, I have a C++ app that needs to get data from that servi...
If you want a service that can be accessed by non .NET code, the appropriate binding to use is basicHttpBinding. This way you will generate a service that adheres to the standard published web service protocol. If you are writing a client in unmanaged C++, calling a web service is supported by ATL. See http://msdn.micr...
3,919,841
3,919,874
How can I get the installed directory for a C++ Windows Service?
I have a C++ Windows service, and I would like to access an executable in the same directory as the service's executable (via the system function). I'd imagine to do this I'll need to find that directory, so that I can refer to the target executable's path. How can I find the directory in which the service is installed...
You can use the GetModuleFileName function. See the Installing a Service example.
3,919,850
3,919,855
Conversion from 'myItem*' to non-scalar type 'myItem' requested
I have this C++ code: #include <iostream> using namespace std; struct MyItem { int value; MyItem* nextItem; }; int main() { MyItem item = new MyItem; return 0; } And I get the error: error: conversion from `MyItem*' to non-scalar type `MyItem' requested Compiling with g++. What does that mean? And what...
Try: MyItem * item = new MyItem; But do not forget to delete it after usage: delete item;
3,920,046
3,920,070
Is it common for a language to evalute undefined as equal to false? If so, why is this done?
UPDATE: Question still unanswered. @Alastair_Pitts: Unless I'm missing something, it's a two part question. The second part, "If so, why is this done?" and not been answered. Believe the question is clear, but if you have any questions -- just let me know. Thanks! undefined = unknown and is a reference to system based...
In many, if not most, languages values are either falsy, meaning that something doesn't exist or lacks value, or truthy, meaning that something exists or has value. The list of falsy values is usually: (these evaluate to false) 0 (zero, the number) '' (an empty string) null (if this value exists) undefined (if this va...
3,920,074
3,920,109
How do I compile a simple c++ program that uses std::thread in cygwin?
#include < thread > results in: error: thread: no such file or directory How can I install/use this library?
Which version of GCC-C++ do you have installed? I believe <thread> is not included with GCC-C++ older than 4.4. However, as you can read from this link: http://gcc.gnu.org/projects/cxx0x.html <thread> is still experimental, and it is still recommended that you use boost.thread in the meantime.
3,920,157
3,920,177
Base class's function pointer points to child class's member function?
I know it sounds awefully confusing, I have a base template class which has a function pointer, a child class(which is no longer a template class) needs to use that function pointer to point to a child class's member function, and I get all kinds of errors.. Did I violate some universal law of C++? here is the pseudo c...
Your code is invalid. Firstly, in C++ to create a pointer to a member function you always have to use operator & and a qualified-name of the member, which means that your call to funcA should look as follows funcA(&Child::funcToCall); // close, but not yet, see "secondly" Secondly, member pointers are contravariant. ...
3,920,238
3,920,370
Bad memory allocation C++ for a vector
I get std_bad_alloc error in the following code. It seems the problems is when I add the matrix to the vector, the program crashes when I get to that line in the debugger. The problem is that only the first two matrices are read from the file, the other two aren't because the program crashes with the above error.
Nowhere in your copy constructor do you set numCols, numRows.
3,920,309
3,920,373
Iterator for vector of pointers not dereferencing correctly
Here is my issue: I have a std::vector<AguiWidgetBase*> which is used to keep track of child controls. I have these two functions to return iterators: std::vector<AguiWidgetBase*>::const_iterator AguiWidgetBase::getChildBeginIterator() const { return children.begin(); } std::vector<AguiWidgetBase*>::const_iterator...
Is there a way I can change my iterators so that it-> works? Not directly, but you could do something like: for(std::vector<AguiWidgetBase*>::const_iterator it = box->getChildBeginIterator(); it != box->getChildEndIterator(); ++it) { AguiWidgetBase* p = *it; p->setText("Hello World"); }
3,920,384
3,920,437
Use _tcstoul to detect invalid string during unsigned long conversion - unable to treat -ve string as invalid value
I try to use _tcstoul for string to unsigned long conversion. However, it doesn't treat -ve string input as invalid input. Is there any workaround for this? Or I had missed out something? #include <cstdio> #include <tchar.h> int main() { { unsigned long iResult(0); TCHAR *pszStopString; iRe...
Adding the missing #include <stdlib.h> (and also changing <cstdio> to <stdio.h>) your code seems to work: C:\test> (cl /nologo- 2>&1) | find "++" Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86 C:\test> cl x.cpp & x x.cpp 2abc : Error occur during conversion! fine C:\test> _ It's uncl...
3,920,801
6,192,665
Implementing custom windows authentication package
I'm building a custom authentication subpackage for MSV1_0 for Windows 7. I've used the msvsubauth sample in from the Windows SDK and I have 2 questions regarding some problems I'm facing with that: When I'm trying just to make sure that the routine get's invoked and set the Auth0 property in the registry to my packag...
Debugging in Winlogon and LSASS makes for the most time consuming debugging. To ease your debugging, you could write a proxy AP that exports the same functions. When loaded, you proxy_ap would Copy the real AP from a known location to a temp locationand. LoadLibrary that DLL, GetProcAddress of everything, and forward...
3,921,012
3,921,052
C++ template work-around
On my C++ project, I recently stumbled upon a little problem: Templates. I declared a class, Data in my header file (which is shared by each .cpp), and gave it a template function. I implemented it in data.cpp. I soon remembered how templates are compiled on the spot, when they are referred to, and this breaks the decl...
There is nothing technically wrong with this, the compiler won't care. It is however very common to stick the template code inside the header files, that is, there is no compelling reason why it should be in a CPP file. About your comment that "all functions" are template functions. Here is where the inefficiency may s...
3,921,151
3,962,159
Creating own implementation of Boost::Archive
I'm currently creating a concept which uses Boost::Serialization and which needs to implement its own Boost::Archive cause the data has to be serialized in a certain way. There is documentation about implementing custom archives in the documentation: http://www.boost.org/doc/libs/1_44_0/libs/serialization/doc/index.htm...
Example implementing Log Archive: http://www.boost.org/doc/libs/1_44_0/libs/serialization/doc/derivation.html Portable Binary archive: http://www.systomath.biz/include/Boost-1_35/libs/serialization/doc/derivation.html#portable_archives
3,921,162
3,921,218
How hide C++ source code from customer
I wish to send some components to my customers. The reasons I want to deliver source code are: 1) My class is templatized. Customer might use any template argument, so I can't pre-compile and send .o file. 2) The customer might use different compiler versions for gcc than mine. So I want him to do compilation at his en...
Contract = good, obfuscation = ungood. That said, you can always do a kind of PIMPL idiom to serve your customer with binaries and just templated wrappers in the header(s). The idea is then to use an "untyped" separately compiled implementation, where the templated wrapper just provides type safety for client code. Tha...
3,921,288
3,921,292
I needn't use the QT's dlls and I want to use libs, when I run exe.How can I do this?
I needn't use the QT's dlls and I want to use libs, when I run exe.How can I do this?
Well you need to statically link the library. See here: http://doc.qt.io/qt-5/windows-deployment.html#static-linking
3,921,294
3,923,850
How do I down-cast a c++ object from a python SWIG wrapper?
The problem: I've wrapped some c++ code in python using SWIG. On the python side, I want to take a wrapped c++ pointer and down-cast it to be a pointer to a subclass. I've added a new c++ function to the SWIG .i file that does this down-casting, but when I call it from python, I get a TypeError. Here are the details: ...
As I commented above, this seems to work ok with swig 1.3.40. Here are my files: c.h: #include <iostream> class Base {}; class Derived : public Base { public: void f() const { std::cout << "In Derived::f()" << std::endl; } }; class Container { public: const Base& GetBase() const { return derived...
3,921,398
3,921,551
Is there any way to make for_each take references?
This cites for_each as follows: template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function f); I have a collection std::list<std::string>, and a function void Do(std::string) works fine when given to for_each along with the iterators. But if I supply a functio...
The error is not with for_each but with bind1st and mem_fun. They simply dont't support what you're trying to do. They cannot handle functions which take reference parameters. You could write your own functor, use boost::bind or wait until you're able to use C++0x lambdas. Example for your own functor: struct LoadShare...
3,921,541
3,922,401
Programming Language for Creating DLL: C++ or C#
This is NOT a Programming doubt! I am going to write a DLL for some application. I have two options to choose from: C++ or C# In which language I should write DLL? Does that affects functionality? I am a completely newbie and Unaware of both C++ and C# (but Some Small programs in C#). What are Pros and Cons about Writt...
A DLL is best written in C :) Let me explain: DLL's were conceived before C++ came into mainstream use. They were created for the C language. You can write DLL's with C++ but you'll be able to easily use them only from applications that were written with the same version of the same compiler as the DLL. A C DLL can be ...
3,921,864
3,921,889
Are friends in c++ mutual?
Possible Duplicate: Friend scope in C++ Are friends in C++ mutual?
class bar { private: void barMe(); }; class foo { private: void fooMe(); friend bar; }; In the above example foo class can't call barMe() You need to define the classes this way in order that the friend be mutual: class foo; // forward class bar { private: void barMe(); friend foo; }; class foo { private:...
3,922,016
3,922,128
Const and non-const access resolves to different overloads?
Let me say we have a simple programming task. But for the sake of clarity I start with few code samples. First of all we written a some kind of data container class but for the purposes of task no matter what the class is. We just need it to behave const-correct. class DataComponent { public: const std::string& get...
Whether a const or non-const member is invoked is determined purely by the constness of the object on which it is invoked, not by some subsequent operation. That determination is made before any consideration of the particular method you're invoking in DataComponent. You could still hack up the required functionality...
3,922,101
3,925,690
Efficiency. Function return values versus output parameters
Function return values versus "output" parameter, which one is faster? I think I best explain using what I am currently working on. // specify identifier and return pointer. SceneNode* createSceneNode(const String& desired_identifier); // f1 // auto-gen identifier and return as string. String createSceneNode(SceneNo...
The difference between mystring = f2(node) and f2(node) are important to understand. In the first case, most compilers will optimize away the copy constructor for returning by value and simply assign the string from the function without the additional copy step. In the case of the second version, most optimizers will...
3,922,206
3,922,273
Profiling line-by-line in C++
I have a C++ program I am trying to optimize. Since I want it to run fast, I am not using a lot of function calls. Most profiling tool I have seen can give you profiling info in a function-call resolution. However, I would like it in a line-by-line resolution. Is there some option like this? I am using Visual Studio 2...
Intel Parallel Amplifier should be capable of what you want. If that is what you want:
3,922,249
3,922,402
How do I get PCRE to work with C++?
This is a newbie question but I hope I can express my question as clearly as possible. I'm trying to do pattern matching in C++. I've downloaded the Win32 version of PCRE from here and I've placed the downloaded pcre3.dll and pcreposix3.dll files into the folder of Dev-CPP's lib folder (I'm using Bloodshed Dev-C++ 4.9...
If you specify the file for #include with angle brackets (<>), then the compiler will only look for that header in the locations for external libraries, in so far as the compiler is aware of them. If you instead use quotation marks (""), then the compiler will also look in the locations for the current project, which t...
3,922,488
3,922,551
Use wildcards with FindWindow api call with mfc
I am using FindWindow in an mfc application. HWND hWnd = ::FindWindow(NULL, _T("foobar v5")); I would like to use FindWindow with wildcards so that I can match just foobar. Thanks
You will have to create your own implementation which should be based on EnumWindows, GetWindowText and GetWindowTextLength which then must allow the wildcards. #include <Windows.h> #include <iostream> #include <string> #include <vector> struct FindWindowData { FindWindowData( TCHAR const * windowTitle ) :...
3,922,860
3,922,928
what is the workaround for floating point inacurracy?
Here's the code snippet: float pNum = 9.2; char* l_tmpCh = new char[255]; sprintf_s(l_tmpCh, 255, "%.9f", pNum); cout << l_tmpCh << endl; delete l_tmpCh; the output is: 9.199999809 What to do in order for the result to be 9.200000000 Note: I need every float number printed with 9 decimals precision, so I don't want...
There is no way a 32-bit binary float number have 9 digits of precision (there is only 7). You could fake it by appending 3 zeroes. sprintf_s(l_tmpCh, 255, "%.6f000", pNum); This won't work if the integer part exhausted a lot of precision already, e.g. 9222.2f will give 9222.200195000.
3,923,136
3,923,576
Pointer to array deletion
I have an array that is passed via a function and assigned to a class member which is a pointer. class ClassA{ unsigned char * pointerToArray; ClassA(unsigned char array[]){ pointerToArray = array; } ~ClassA(){ //what to do here } }; Now I have this second class which uses this class ClassB { std::list...
Your first sentence already shows all the the confusion: Hi, I have an array that is passed via a function and assigned to a class member which is a pointer. You cannot "pass an array". You can pass pointers or references to arrays or array elements to functions. The type of the parameter array in the constructor for...
3,923,373
3,924,577
Searching std::unordered_set by hash value and predicate
How can I search a std::unordered_set knowing hash value and having some predicate object? (The predicate determining equivalence by pred(x) && pred(y) meaning x == y.)
Well, you could ignore the hash value and iterate the entire unsorted_set testing the predicate. Not the ideal efficiency, since you'd prefer to only iterate one bucket, but it does what you ask. Standard unordered_set has an interface begin(size_t) to get an iterator for a particular bucket (by number), and an interfa...
3,923,384
3,923,449
What is the best practice in C++ to declare objects within classes?
I'm working on a class library in VC++ that shall have ref classes and some native code. Now, I need to use five native objects from an external framework. those objects must be declared on the heap NOT on the stack. I want encapsulate those objects in some sort of a structure knowing that constructors need to be calle...
I'm not sure I know exactly what you're asking. Constructors always need to be called on objects whether they are on the heap or the stack. If you meant that you want something to automatically call destructors for heap allocated memory, then you can use either std::auto_ptr or boost::shared_ptr. Note that these are...
3,923,411
3,923,832
Designing and coding a non-fragmentizing static memory pool
I have heard the term before and I would like to know how to design and code one. Should I use the STL allocator if available? How can it be done on devices with no OS? What are the tradeoffs between using it and using the regular compiler implemented malloc/new?
Will try to describe what is essentially a memory pool - I'm just typing this off the top of my head, been a while since I've implemented one, if something is obviously stupid, it's just a suggestion! :) 1. To reduce fragmentation, you need to create a memory pool that is specific to the type of object you are allocati...
3,923,417
3,923,583
May a compiler optimize a reference to constant parameter to constant value?
Consider following function: void func(const char & input){ //do something } Apparently it makes sense for the parameter to be constant value not reference to constant regarding size of the char type, Now may a compiler optimize that to constant value so that it'll be the same as following ? void func(const char inpu...
Like someone stated, but was sadly downvoted (not sure why he did delete his answer), the compiler can do any and everything as long as the observable behavior is the same as if it did not do anything different. It's self-expanatory that if your function writes into the reference, and a global variable was passed as a...
3,923,464
3,924,059
Would using a virtual destructor make non-virtual functions do v-table lookups?
Just what the topic asks. Also want to know why non of the usual examples of CRTP do not mention a virtual dtor. EDIT: Guys, Please post about the CRTP prob as well, thanks.
Only virtual functions require dynamic dispatch (and hence vtable lookups) and not even in all cases. If the compiler is able to determine at compile time what is the final overrider for a method call, it can elide performing the dispatch at runtime. User code can also disable the dynamic dispatch if it so desires: str...
3,923,558
3,923,577
Why this scanf returns false?
This scanf should always return true until I input none numeric input, but this scanf never executes while loop. Why? Sample input: 10.0 5.0 Press [Enter] to close the terminal ... Code: #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { float a, b; while ( scanf("%f %f", &a, &b) == 1 ) ...
scanf returns the number of items read, which in this case is 2.
3,923,803
3,924,161
In C++, how to initialize static member of a private class declared inside a Singleton template?
Ok, I should simply tell that I want to make a base Singleton class that I can inherit from, and the way I want to achieve that is by a template. In order to avoid memory leaks, I do not use directly a pointer to the instance, but a private class that will handle deleting the pointer. Here is my actual code (not workin...
Here is a simpler way of writing a CRTP Singleton without a memory leak: template <class T> class Singleton { friend class T; private: Singleton() {}; ~Singleton() {}; Singleton(const Singleton&); // not implemented const Singleton& operator=(const Singleton&); // not implemented public: static T* pGetInst...
3,924,082
3,924,252
How to dynamically set your apps' Base priority to 31?
I have the following problem - I want to set my C++ application's Base priority to 31 if that is possible or at least set its current priority to 31. So I need a simple example like set priority to 31; for (i=0;i<100000;++i) { printf("hello world"); } set priority to 8 or keep 31 if possible
In order to set your priority class to the realtime priority class, you need to be running with elevated privileges (as an admin). As others have asked, are you SURE you want to do this? If you set your priority that high, it will lock out all other processing on the system (even the mouse will stop working). One opti...
3,924,123
3,924,180
Win32 C/C++ - Detecting if IPv6 is installed
Is there a way to detect if the IPv6 protocol is installed without looping through all available IP addresses and checking for IPv6 addresses? I can't find anything on msdn.
You can use WSCEnumProtocols to detect if IPv6 is available on the machine.
3,924,135
3,924,386
I have lots of questions about c++ that are really confusing me
I started learning c++ about 3 weeks ago after 2 years of java. It seems so different but im getting there. my lecturer is a lovely guy but any time i ask a question as to why something is that way or this way. he just responds "because it is". Theres lots of comments in the code below with a few random questions, but...
My quick answers without double checking (its been awhile since I've developed in C++) are: arraytotal has not been initialized I suspect that your compiler flags this as an error to make sure you do it. If you don't, you can't be sure what it will be initialized to. Traditionally for debug builds, C/C++ initialized...
3,924,439
3,924,480
In Qt (4.6), is it ok to call slots directly?
I found myself in the need of having to call a slot directly. I think it's perfectly fine doing it as long as it makes sense in your design. What do you think? Thanks
Yes.. Slots are just normal functions and you can call them directly.. From docs, A slot is called when a signal connected to it is emitted. Slots are normal C++ functions and can be called normally; their only special feature is that signals can be connected to them.
3,924,459
3,925,722
C++ network programing in linux: Server Questions
I am learning how to network program using c/c++ and I have created a server(TCP) that is suppose to respond in specific ways to messages from a client in order to do this I created a class that the server class passes the message to and returns a string to report back to the client. Here is my problem sometimes it rep...
You are calling handleMessage twice. You didn't post the code, but it looks like you're returning a string. It might be better to do: string temp = ash.handleMessage(buf); int size_of_temp = temp.length(); This would avoid repeating any action that takes place in handleMessage.
3,924,829
3,924,879
why is concurrent_queue non-blocking?
In the concurrency runtime introduced in VS2010, there is a concurrent_queue class. It has a non blocking try_pop() function. Similar in Intel Thread Building Blocks (TBB), the blocking pop() call was removed when going from version 2.1 to 2.2. I wonder what the problem is with a blocking call. Why was it removed from ...
From a comment from Arch Robison, and it doesn't get much more "horse's mouth" than that (a): PPL's concurrent_queue has no blocking pop, hence neither does tbb::strict_ppl::concurrent_queue. The blocking pop is available in tbb::concurrent_bounded_queue. The design argument for omitting blocking pop is that in many c...
3,924,926
3,924,979
cannot convert parameter 1 from 'char' to 'LPCWSTR'
I keep getting this error: cannot convert parameter 1 from 'char' to 'LPCWSTR' int main(int argc, char argv[]) { // open port for I/O HANDLE h = CreateFile(argv[1],GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL); if(h == INVALID_HANDLE_VALUE) { PrintError("E012_Failed to open port"); can ...
It should be int main(int argc, char* argv[]) And HANDLE h = CreateFileA(argv[1],GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
3,924,957
3,925,016
trouble with output directory for OpenCV VideoWriters
I'm a math undergrad and have little programming experience. I'm interested in computer vision however. Tried to follow the Learning OpenCV book but its slightly outdated. How do i save the resulting video file in my linux home directory? for eg "/home/user/..", thanks in advance, this is my first post and i know i won...
Have you tried passing the full path to cvCreateVideoWriter? CvVideoWriter *writer = cvCreateVideoWriter( "/home/user/out.avi", CV_FOURCC('M','J','P','G'), fps, cvSize(frameW,frameH), isColor );
3,925,142
3,925,194
Does C++11 for loop allow new or better optimizations?
In C++11 we can now do : void dosomething( std::vector<Thing>& things ) { for( Thing& thing : things ) { dofoo( thing ); wiizzz( thing ); tadaa( thing ); } } I know that the addition and use of lambda is syntactic sugar but it provide interesting optimization opportunities. What ab...
It's just a syntactic sugar since the standard says that it's equivalent to a loop with iterators [ Edit: this means it doesn't provide any additional information to the compiler compared to the equivalent for loop — end edit ]. You may get a better performance though since it's equivalent to: for(auto iter = con.begin...
3,925,244
3,925,393
Export part of the namespace of a class
I have a class that includes an enum: class appearance{ // ... stuff ... enum color {BLUE, RED, GREEN}; }; I would like to attach part of the namespace (with using) so that I can refer to the value of the BLUE simply as BLUE, rather than appearance::BLUE. At the same time, I would like to keep the enum within the ...
I don't think it can be done. AFAIK, you can use using appearance::color in another class or structure as stipulated here. A using declaration in a class A may name one of the following: A member of a base class of A A member of an anonymous union that is a member of a base class of A An enumerator for an enumera...
3,925,255
3,925,411
cvblob compile error in Visual C++ 6.0
I'm using Microsoft Visual C++ 6.0 and Microsoft Visual Studio 2008 to develop an academic computer vision project. In this project i need to use OpenCV 1.1 (http://opencv.willowgarage.com/) and CvBlob (http://code.google.com/p/cvblob/). I tried to compile this project with Microsoft Visual Studio 2008 and it compile...
C2371 - VC6 was sloppy with scope of local variables. Should be able to fix this by making the code use variable names unambiguously. C2664 - looks like failure to initialize a vector using deque iterators - wrong overload on vector::vector() being called? Probably have to work around this by manually copying the dequ...
3,925,410
3,925,469
Question about line.length();
does line.length(); include end line chars? For example Hello World How long would this be 11 or 12?
std::string s1 = "Hello World\n"; std::cout << s1.length() << std::endl; This prints 12. The new line is included in the length.
3,925,836
3,925,891
How to Auto send SMS via Broadband USB dongle?
One of my internet connections is via a USB dongle. As well as accessing the internet I can use the SIM card contained inside to send SMS texts in the exact same fashion as a SIM card housed in my mobile phone. (I know, I really am a technical superhero...) Anyway, I wish to be able to send a message at a pre-determi...
You could look into the AT commands as that is how it works. By sending an AT command to the usb dongle, one could send a text, the ability to send a message at a pre-determined time would have to be implemented logically in the code outside of the communications with the usb dongle. Something like this in pseudo code ...
3,926,305
3,926,349
typedef templates in global scope
using template classes I usually make some typedefs like: typedef super<puper<complex<template<type> > > > simple_name I usually do it in 2 ways: template <class A, ...> struct Types { typedef ... } template <class A, ...> class Part_Of_Logick { public: typedef ... } Is it possible to set typedefs at...
I understand that you mean writing a templated typedef that will create a second template with some of the arguments of the first template fixed. If that is the question, no, not in the current standard. In the upcoming c++0x standard you will be able to do: template <typename A, typename B> a_template; template <typen...
3,926,336
3,927,622
How do compile a simple program using boost::thread in cygwin?
I installed the boost package from cygwin and have a directory /usr/include/boost that includes a bunch of *.hpp files, including thread.hpp, which I need to include in the c++ file, via #include <boost/thread.hpp> Also, several *.a files seem to be related to boost::thread. $ ls /usr/lib/libboost_thread* -1 /usr/lib/...
EDIT (removed -gcc part): g++ sample.cpp -lboost_thread-mt. You may need to add -lpthread or -pthread as well. If still no luck, please post the errors you get. HTH
3,926,340
3,926,438
c++ array to vector issue
Im trying to copy an array to a vector, however, when the data is copied to the vector its different from that of the original array. int arraySize = 640000; std::vector<unsigned char> vector_buffer; unsigned char buffer[arraySize]; populateArray(&buffer); for(int i = 0; i < arraySize; i++) cout << buffer[i]...
The int arraySize = 640000; needs to be const in standard C++. g++ allows variable length arrays as a C99-inspired language extension. It's best to turn that extension off. :-) std::vector<unsigned char> vector_buffer; unsigned char buffer[arraySize]; OK when arraySize is const, but will not compile with e.g. Visual ...
3,926,415
3,934,174
MSVS2010 linker error sadness - not entirely sure what is wrong
I am using a library of code from a tutorial for providing functionality for passing function points of non-static member functions to a function that expects a static function pointer, probably helps to know what I am suing, so here is the link http://www.codeproject.com/KB/cpp/thunk32.aspx This code uses the Boost li...
Ok, so I have managed to solve this now. Michael Burr nicley said that ??= is basically the same as typing # but in a way that people who dont have the hash symbol can type it, see Purpose of Trigraph sequences in C++? Hans Passant then got the ball rolling for me buy letting me know that I had not fully linked in stu...
3,926,530
3,926,915
A Singleton that is not globally accessible
I just wondered what the best way is to get rid of the globally available static getInstance() in a Singleton. I do not want my Singleton classes being accessed from every point in my program. I thought about maybe having a create() public static function that creates one object and returns it but one cannot call this ...
You said that "creating one a second time would damage the whole application.". My response is: so don't make more then one. In C++, the type system is too weak to easily ensure this at compile-time. We can still write up a utility to approximate it at run-time, though. Note, though, that this in no way implies you sho...
3,926,625
3,926,671
Simple software license key server suggestions?
My boss wants a quick, simple to integrate, simple to host software licensing server to enforce license activations and expirations. We have to integrate it with a C++ Windows Service application. I would not like to host the service in our office for the same reason we don't host our own website in our office. The ser...
Flexnet Publisher does what you want - not sure of pricing model though. EDIT: Flexnet appear to be pricey and non-hosted. Try this thread for more options: https://stackoverflow.com/questions/443064/alternatives-to-flexnet-publisher-reprise (Dead) Orion looks promising. EDIT 2: The SO thread above was removed. Some al...
3,926,637
3,926,690
How to intentionally cause a compile-time error on template instantiation
Sometimes when coding with C++ templates, you want to prevent users from instantiating a specific specialization or set of specializations, because the result would be nonsensical. So you can define a (specific or partial) specialization whose definition, if instantiated, would cause a compiler error. The goal would ...
You could just omit defining it. template <typename T> struct MyClassTemplate<T*>; You could also derive from a non-defined specialization template <typename T> struct invalid; template <typename T> struct MyClassTemplate<T*> : invalid<T> { }; Note that explicit specializations that declare classes or functions will ...
3,926,929
6,614,779
Const function specification in UML
If I have fnc: class AClass { void fnc() const; }; Am I supposed to provide const modifier in UML class diagram while listing this fnc or not?
You are the only person who will identify your UML Diagrams details. So UML does not dictate(if it dictate who cares:-)) you anything... You can show it or not . The real question is: Why you draw that diagram? Who is your audience? [ Who will read diagrams] and For yourself or for your audience, is it necessary sho...
3,927,138
3,927,186
Are there C++ versions of PHP's fsockopen, fread, fwrite, fclose?
Are there C++ versions of PHP's fsockopen, fread, fwrite, fclose or anything similar? I'm using Windows (MFC) and TCP if that changes anything.
there are analogous functions for all of thoes take a look at the winsock api for particular functions. MFC is a wrapper for much of the win32 api and has a Csoket and CAsyncSocket abstract sockets.
3,927,162
3,928,372
Runtime or compile time for platform-specific libraries?
I'm creating a library in C++. It links against Windows libraries on Windows and Linux libraries on Linux. It's abstracted, all is well. However, is it feasible to dynamically detect, load and use libraries (and copying header files for use) so it could be used on any platform if it was running under LLVM JIT?
Unfortunately, the LLVM intermediate representation in the bitcode files is not machine completely machine independent. You could probably get away with x86 Linux and Windows, but that same bitcode would probably not run on x86_64 systems, for example.