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
2,168,241
2,171,570
Is it required to add 'extern C' in source file also?
I found some code recently where extern "C" was added in source file also for functions. They were also added in the header files where they were declared. I was under the assumption that adding 'extern "C" in header files was sufficient. Where should extern "C" blocks be added? UPDATE: Suppose I am compiling my C cod...
Since you mean extern "C" { ... } style guards, these declare some functions to be of "C" linkage, rather than "C++" linkage (which typically has a bunch of extra name decoration to support things like overloaded functions). The purpose, of course, is to allow C++ code to interface with C code, which is usually in a ...
2,168,329
2,168,653
RegQueryValueEx() always returns only 4 bytes of the string
What im doing wrong this time? The following code always returns 4 bytes only, instead of the whole string: HKEY hkey; DWORD dwType, dwSize; char keybuffer[512]; if(RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("software\\company name\\game name"), 0, KEY_READ, &hkey) == ERROR_SUCCESS){ dwType = REG_SZ; dwSize = sizeo...
I see two more potential pitfalls here. First, as Francis mentioned, you should check the return value. Do the 4 bytes actually correspond to the string characters you expect? They might be anything. From the documentation: If the buffer specified by lpData parameter is not large enough to hold the data, the function ...
2,168,362
2,168,379
iostream use of << to construct string
How can << be used to construct a string ala int iCount; char szB[128]; sprintf (szB,"%03i", iCount);
using namespace std; stringstream ss; ss << setw(3) << setfill('0') << iCount; string szB = ss.str();
2,168,365
2,169,201
In what language is there a "guard" keyword or concept?
I recently tried to understand a C++ program that was written by somebody who I assume had a background in functional programming: For example, he had declared a closure class which he extensively used and which does somewhat resemble what is known as a closure in functional programming. Another class was called a guar...
To me it sounds like he was using RAII. The class constructor/destructor is used to symetrically handle some form of resource allocation/release in an exception safe context (What Java programmers would call finally {} as the destructor is guranteed to be called.). This is a very common C++ idiom and is ued extensively...
2,168,446
2,168,466
Method of derived class needs to downcast its parameter
Here is a sample code: class Base { public: virtual void common(); }; class Derived { public: void common(); virtual void spec(); // added function specific for this class }; class BaseTracker { public: void add(Base* p); private: vector &lt Base* &gt vec; }; class DerivedTracker { public: v...
It sounds like the Tracker class would best be a template instead of being derived from a common ancestor: template<typename Element> class Tracker { public: void add(Element* p); private: vector< Element* > vec; }; typedef Tracker<Base> BaseTracker; typedef Tracker<Derived> DerivedTracker; You could then add a...
2,168,996
2,169,088
How to write unicode character farsi in C++ in ms-dos console?
How to write unicode character farsi in c++ in ms-dos? cout<<"Helo world"<<"سلام جهان";
#include <iostream> #include <locale> #include <string> int main() { using namespace std; wstring wcs = L"中文"; locale old = wcout.imbue(locale("") ); // "" is environment's default locale wcout<<wcs<<endl; wcout.imbue(old ); // restore old locale }
2,169,092
2,319,728
Low-Level C++ App Crashes on Windows Vista/7 Unless Run in XP Compatibility Mode
I have a low-level (like really low-level, it's basically all IOCTL calls and several calls to enumeration APIs) that crashes sporadically on Windows Vista/7 on clients' machines. Unfortunately, I have not been able to procure any crash dumps but one helpful user did mention that running the program in XP Compatibility...
This is very odd, but I was calling ZwQueryVolumeInformationFile with FsInformationClass set to FileFsVolumeInformation. I had passed in a buffer of FILE_FS_VOLUME_INFORMATION first normally allocated, then overallocated to (sizeof(FILE_FS_VOLUME_INFORMATION) + sizeof(TCHAR)*FILE_FS_VOLUME_INFORMATION->VolumeLabelLengt...
2,169,322
2,169,355
When to use pointers in C++
I just started learning about pointers in C++, and I'm not very sure on when to use pointers, and when to use actual objects. For example, in one of my assignments we have to construct a gPolyline class, where each point is defined by a gVector. Right now my variables for the gPolyline class looks like this: private: v...
The general rule of thumb is to use pointers when you need to, and values or references when you can. If you use vector<gVector3> inserting elements will make copies of these elements and the elements will not be connected any more to the item you inserted. When you store pointers, the vector just refers to the object ...
2,169,384
2,169,658
Is CLIM possible in C++?
CLIM = Common Lisp Interface Manager, it's like the REPL, ported to the GUI. Is something like this similar possible in C++? If so, pointers? Thanks!
Here's a REPL built atop GNU C++: http://www.artificialworlds.net/wiki/IGCC/IGCC There's no reason why it shouldn't work okay these days - it probably builds up a short program from successive statements, which on a modern machine will compile and run to display output in short order. From the look of the examples, it ...
2,169,387
2,169,551
X throws out errors when forkpty is called. (C++)
When my program gets to this line: pid_t nPid = forkpty( &m_nMasterFD, NULL, NULL, NULL ); Outputs this: X Error: BadIDChoice (invalid resource ID chosen for this connection) 14 Extension: 148 (RENDER) Minor opcode: 17 (RenderCreateGlyphSet) Resource id: 0x3600002 <unknown>: Fatal IO error 4 (Interrupted sys...
forkpty() forks your process. You need to close the filedescriptors first, in particular the connection to the X server in your child process. This means you likely cannot use forkpty , but have to use openpty(), fork(),close filedescriptors in the child process, logintty/()
2,169,441
2,169,451
C++ typedef question
if I make a typedef someobject* pntr; I can use this typedef to make a pointer to point to an object of type someobject. but can I also use a pointer made from this typedef to point to an array of someobject?
Yes: pntr p = new someobject[10]; However, it is considered poor style in both C++ and C to use typedefs to disguise the fact that something is a pointer, so don't do this.
2,169,460
2,169,505
Polymorphism by function parameter
Ok - this may be a very stupid question, but it's been bothering me. Is there a language where class Animal; class Ape : public Animal {...} void doStuff(Animal* animalPtr) { cout << "doing animal stuff" << endl; } void doStuff(Ape* apePtr) { cout << "doing ape stuff" << endl; } Animal *ape = new Ape(); doSt...
Yes, there are! This is called multiple dispatch. The Wikipedia article is very good. Sadly, it seem to only be supported via language extensions for most popular languages, but there are a few (mostly esoteric) languages which support it natively.
2,169,828
2,169,912
Is there a better (more modern) tool than lex/flex for generating a tokenizer for C++?
I recent added source file parsing to an existing tool that generated output files from complex command line arguments. The command line arguments got to be so complex that we started allowing them to be supplied as a file that was parsed as if it was a very large command line, but the syntax was still awkward. So I...
Ragel: http://www.complang.org/ragel/ It fits most of your requirements. It runs on Windows It doesn't declare the variables, so you can put them inside a class or inside a function as you like. It has nice tools for analyzing regular expressions to see when they would backtrack. (I don't know about this very much, s...
2,169,867
2,219,028
How to detect the current input language?
I am looking for a working code snippet for Symbian S60 5th edition in which: a) an application can detect the current input language (not the UI language); b) an application can receive notifications when current input language is changed. The function CurrentLanguage() from CPtiEngine always returns NULL, so that ...
I eventually found the answer on my own. Here is the code: CAknSettingCache& cache = CAknEnv::Static()->SettingCache(); TLanguage lang = cache.InputLanguage();
2,169,916
2,170,010
How to check if button is pressed and working on LPT port in C++
I have a button I got out of a random item around the house and I wanna hook it up to my LPT port and check if its pressed or not in C++ and if it is display a message.
Your best bet is to use the inpout32.dll which will enable you to read/write from/to the LPT port. The usage of direct addressing of hardware ports is restricted, the dll will enable you to get around the restriction as it executes an internal driver which is already built into the dll and therefore communicating with ...
2,169,920
2,169,928
Do <cctype> functions work with Unicode?
Page 601 of the C++ Special Edition says... In <ctype.h> and <cctype>, the standard library provides a set of useful functions for dealing with ASCII and similar character sets. Would Unicode fall under this "similar character sets" category?
Unicode support has been a major pain point of the language. You will have to set a locale for non-ANSI and use the wchar_t variants. The exact meaning of the wchar_t varies with implementation. E.g: setlocale(LC_CTYPE, "en_ca.UTF-8"); Take a look at the the Unicode Consortium page on locales.
2,169,932
2,170,078
non-class rvalues always have cv-unqualified types
§3.10 section 9 says "non-class rvalues always have cv-unqualified types". That made me wonder... int foo() { return 5; } const int bar() { return 5; } void pass_int(int&& i) { std::cout << "rvalue\n"; } void pass_int(const int&& i) { std::cout << "const rvalue\n"; } int main() { pass_int(foo())...
The committee already seems to be aware that there's a problem in this part of the standard. CWG issue 690 talks about a somewhat similar problem with exactly the same part of the standard (in the "additional note" from September, 2009). I'd guess new language will be drafted for that part of the standard soon. Edit: I...
2,169,948
2,172,689
Using code generated by Py++ as a Python extension
I have a need to wrap an existing C++ library for use in Python. After reading through this answer on choosing an appropriate method to wrap C++ for use in Python, I decided to go with Py++. I walked through the tutorial for Py++, using the tutorial files, and I got the expected output in generated.cpp, but I haven't f...
Py++ generates you syntax you use along with boost::python to generate python entry points in your app. Assuming everything went well with Py++ you need to download the Boost framework, and add the boost include directory and the boost::python lib to your project then compile with the Py++ generated cpp. You can use wh...
2,170,064
2,170,102
STL-Like range, What could go wrong if I did this?
I am writing (as a self-teaching exercise) a simple STL-Like range. It is an Immutable-Random-Access "container". My range, keeps only the its start element, the the number of elements and the step size(the difference between two consecutive elements): struct range { ... private: value_type m_first_element, m_element...
The standard algorithms don't really use operator[], they're all defined in terms of iterators unless I've forgotten something significant. Is the plan to re-implement the standard algorithms on top of operator[] for your "ranges", rather than iterators? Where non-mutating algorithms do use iterators, they're all defin...
2,170,222
2,170,237
PThread vs boost::thread?
Having no experience with threading in the past, which threading technique in C++ will be the easiest for a beginner? boost::thread or pthreads?
Go for boost::thread. It's closely related to the work on the upcoming C++ standard threads, and the interface is quite easy to use and idiomatic to C++ (RAII instead of manual resource management).
2,170,523
2,171,721
CoreAudio AudioUnitSetProperty always fails to set Sample Rate
I need to change the output sample rate from 44.1 to 32.0, but it always throws an error, Out: AudioUnitSetProperty-SF=\217\325\377\377, -10865. I don't know why it will let me set it for input, but then not set it for output. My code is: - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { OSStatus...
With the DefaultOuput AudioUnit you only set the input side of the AudioUnit to the format you wish to render. The output side of the unit will match what you specify on the input side but you cannot set it yourself. Try this after you have set the input stream format and you'll see that you are all set to go... Float6...
2,170,541
2,170,565
What operations are thread-safe on std::map?
Suppose I have: stl::map<std::string, Foo> myMap; is the following function thread safe? myMap["xyz"] ? I.e. I want to have this giant read-only map that is shared among many threads; but I don't know if even searching it is thread safe. Everything is written to once first. Then after that, multiple threads read fro...
In theory no STL containers are threadsafe. In practice reading is safe if the container is not being concurrently modified. ie the standard makes no specifications about threads. The next version of the standard will and IIUC it will then guarantee safe readonly behaviour. If you are really concerned, use a sorted a...
2,170,637
2,170,664
How to view source code of header file in C++?
similar to iostream.h ,conio.h , ...
The standard library is generally all templates. You can just open up the desired header and see how it's implemented†. Note it's not <iostream.h>, it's <iostream>; the C++ standard library does not have .h extensions. C libraries like <string.h> can be included as <cstring> (though that generally just includes string....
2,170,725
2,170,756
How does the following foward-declared multi-inheritance pointer converted code work?
In the followint code, how does the pointer conversion & multi-inheritance play together? class Foo { public: virtual void someFunc(); }; class Bar; void someWork(Bar *bar) { ((Foo*) bar)->someFunc(); } class Bar: public Zed, public Foo { ... virtual void someFunc() { ... do something else ... } } Bar bar; ...
This doesn't work and it isn't doing quite what you think it is. Your use of the c-style cast: (Foo*) bar is incorrect in this case. What you are trying to do is upcast the Bar* to a Foo* (i.e., perform a static_cast from a pointer to a dervied class to a pointer to a base class). Since the definition of Bar is no...
2,170,785
2,170,804
Guarantees on address of baseclass in C++?
In C struct's, I'm guaranteed that: struct Foo { ... }; struct Bar { Foo foo; ... } Bar bar; assert(&bar == &(bar.foo)); Now, in C++, if I have: class Foo { ... }; class Bar: public Foo, public Other crap ... { ... } Bar bar; assert(&bar == (Foo*) (&bar)); // is this guaranteed? If so, can you give me a refere...
There is no guarantee. From the C++03 standard (10/3, class.derived): The order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified.
2,170,886
2,170,904
Dynamic array allocation in C++ question
I have a struct of type Duplicate I have a variable of type int called stringSize, it has a value of 5 I am creating a dynamic array: Duplicate *duplicates; duplicates = new Duplicate[stringSize - 1]; Later I delete[] duplicates; I'm getting one member in that array only? I've verified that stringSize - 1 = 4 with a d...
Duplicate *duplicates; duplicates = new Duplicate[stringSize - 1]; Indeed gives you duplicates[0-3] (Assuming stringSize - 1 is 4, like you say). How are you determining you're getting less? I suspect you may be doing something like: sizeof(duplicates) / sizeof(duplicates[0]), and on an off-change getting one. The abo...
2,170,972
2,171,022
Seeking tool to graphically show (header) file dependancies in C/C++
I know that header guards avoid (most) trouble; call me @n@l if you like, but I just don't like a sloppy header-file tree. If I draw on paper a box for each header file and connect them by lines representing #include, I like to see a neat hierarchy. But what I usually see is a complex web. Maybe I am @n@l, but to...
Doxygen can do this for you if you use it along with the dot tool. Here is an example: http://www.neuraladvance.com/json-c/html/json_8h.html
2,171,041
2,171,620
how to change address of variable?
i have Tree<std:string> tree; now new Tree<std:string>; leads to a pointer, how can i change address of tree to that of pointer generated by new?
Making C++ code look like Java is a bad idea, the two languages are very different. That said, in C++ operator new returns a pointer to the allocated object. Tree<std::string> * tree = new Tree<std::string>; tree->do_something(); You can also bind a reference to your object. Tree<std::string> & tree2 = *tree; tree.do_...
2,171,047
2,171,153
bad_alloc in detail?
I work on a game project. Recently, we run into a problem which we catch a "bad_alloc" exception when we load/unload different scenes for about three times. Eachtime we load a scene, we first load the compressed .zip folder into the memory and then extract game objects from it. Since we don't have any memory profiler ...
If you are allocating all that memory at a time (only one new), probably the heap is too fragmented to find enough contiguous memory to allocate what you requested. That could be solved by allocating the new scene by parts.
2,171,081
2,171,186
how c++ implements the polymorphism internally?
Respected Sir! i should tell you that what i know and what i don't know about the asked question so that you can address the weak area of my understanding. i know that c++ implements the polymorphism by using the Vtable which is array of pointers each pointer points to the virtual function of the class, each class in ...
I think you should draw attention to Stanley B. Lippman's book "Inside C++ object model". Lets look for internal presentation for your classes: Virtual Table for person and teacher |---------------| +---> |------------------------| | name | | | "type_info" for person | |---------------| | |---------...
2,171,181
2,171,200
Declaring a variable as a "Class" datatype, without calling the "Class" constructor?
Forgive me if I'm just blatantly missing something, but I'm trying to make the transition from structs and c to classes and c++. Heres what I'm trying to do: A have a "Checkers" class and a "Board" class. Now with structs, I could just create an array of Checkers in my "board.cpp" file by doing: Checker checkers[2][12]...
Create a default constructor. Then use an initial function. I do recomend you use STL vector.
2,171,247
2,171,559
standalone tool for generating makefile(s) from Eclipse's .cproject file?
Is there a standalone tool, that can be ran from a shell script, to generate a makefile from the .cproject? Actually, the same functionality as the CDT itself, but that can be non-interactive. As is probably obvious, I want to be able to run a script that checkouts and builds the software, comprising from several C++ p...
I know that there was discussions on the CDT-dev mailinglist a few months back about having a command-line tool for building CDT projects. Writing such a tool is really not very difficult (there was an example mentioned), it is simply a matter of defining your own Eclipse-application, load the project, and build it. Se...
2,171,263
2,191,822
Release a socket in Boost.Asio (opposite of assign), or don't transfer ownership
There is a function assign in Boost.Asio sockets, however I'm looking for something like release/unassign that would transfer the ownership on socket back to user. or some type of assign that would not transfer ownership to socket class, so it would not close it when destroyed. I'm aware of this solution but it inv...
I couldn't find any such way in the .hpp files (Boost 1.35), so I think you'll have to patch ASIO yourself and add a release() method. When done, you could keep the patch for yourself, post it on your website (or here), or submit it back to Boost. Do try the Boost mailing lists. The people there might tell you whether...
2,171,540
2,171,554
C++ destructor example
My C++ is a little rusty but I have made a program that reverses a linked list and now I am trying to write the proper destructors for it but I don't know exactly what to destroy. Here are my class definitions: class LinkedList { private:ListElement *start; public:LinkedList(); public:void AddElement(int va...
For the ListElement make the value 0 and the link 0(NULL). You don't need to reset any of the values in the destructor, as values won't exist after the destructor executed. The main thing you need to be sure of is that all elements allocated on the heap (i.e Using new) are deleted using delete (or delete [] in the ca...
2,171,650
2,171,759
Callback for button in Qt Designer?
I just started using QtCreator tonight, and it seems it puts all of the interface stuff inside of the ui file. I followed a tutorial to create a resource for my icons, then I added them to a menu bar at the top. I need to make a connection when one of them is clicked though, and cannot figure out how to make a callback...
Menu bar items are action objects. To do something when they are clicked, you need to catch the triggered() signal from the action. Read more about signals and slots here. To do this, you need to declare a new slot in your MainWindow class. Qt also supports doing this automatically, without the need to connect anything...
2,171,715
2,171,729
Do we have design patterns in C++ as we have in java?
As we have so many design patterns in java, like wise do we have any in c++.Or can we use the same sort of patterns in c++.
The original book on Design patterns (Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four) predates Java. The examples in there are in C++ and Smalltalk. Design patterns are applicable to many object-oriented programming languages; maybe it's just that in Java they are usually so ubiquito...
2,171,799
2,171,838
conversion operator as standalone function
Why does C++ require that user-defined conversion operator can only be non-static member? Why is it not allowed to use standalone functions as for other unary operators? Something like this: operator bool (const std::string& s) { return !s.empty(); }
The one reason I can think of is to prevent implicit conversions being applied to the thing being cast. In your example, if you said: bool( "foo" ); then "foo" would be implicitly converted to a string, which would then have the explicit bool conversion you provided applied to it. This is not possible if the bool op...
2,171,891
2,173,326
Using std::streams to format output
I have an object that I want to be able to stream. But I want to be able to stream it in different ways by using different formats, or should I say ways to describe this object. And I wonder how this is supposed to be solved with streams. What I want is to be able to use a generic format and use some kind of format ad...
Try using the Visitor design pattern: struct Object_Writer_Interface { virtual void write_member_i(int value) = 0; virtual void write_member_c(char value) = 0; }; struct Object { int i; char c; void write(Object_Writer_Interface * p_writer) { if (p_writer) { p_writer->wr...
2,171,892
2,171,921
Use struct as base for derived class in C++
Is it possible to have a class inheriting from a struct? More specifically, how can I wrap a C struct with a class, so that I can pass class pointers to methods that requires struct ptr and cast back when I receive the pointer in e.g. callbacks? (Or even more specifically, the address of the class should be same same a...
You just derive from the C struct. In C++, the only difference between a struct and a class is that the latter's default member accessibility is private, while the former's is public. If only single inheritance is involved, the class's address should be the same as the struct's which acts as a base class. If the inher...
2,171,975
2,171,997
Completely OO C++ SQL Wrapper?
So I'm looking for a SQL wrapper for C++ that completely hides any textual SQL statements. I just can't seem to find any, I'm wondering why all the wrappers out there seem at some point to want you to write a textual SQL statement such as: SELECT * FROM stock WHERE item = 'Hotdog Buns' here's MySQL++ for example: mys...
Check out hiberlite and litesql.
2,171,996
2,172,058
Memory allocators for a native C++ library to be used by C#
I'm writing some native C++ code which needs to be called from C# (and I can't replace the C++ native code with C# code). I found memory corruptions while allocating/deallocating some memory in the native C++ code using malloc/free. Then I used LocalAlloc/LocalFree and HeapAlloc/HeapFree and had the same problems. The ...
As long as the C# side of the code uses the compiler's /unsafe switch and the fixed keyword used for holding the buffer of data, I think you should be ok. As to the question of your memory allocation, it may not be the C++ memory allocation code that is causing the problem, it could be the way how the C++ code is inte...
2,172,053
2,172,056
C++, can I statically initialize a std::map at compile time?
If I code this std::map<int, char> example = { (1, 'a'), (2, 'b'), (3, 'c') }; then g++ says to me deducing from brace-enclosed initializer list requires #include <initializer_list> in C++...
Not in C++98. C++11 supports this, so if you enable C++11 flags and include what g++ suggests, you can. Edit: from gcc 5 C++11 is on by default
2,172,293
2,172,311
Getting Unresolved External error
I have made a class and it compiles with no syntax errors, but I get 6 unresolved external symbols? THE CLASS: struct CELL { private: static bool haslife; static int x; static int y; public: static bool has_life() { return haslife; } static void set_coords(int xcoord, int ycoord) { ...
Don't define all of the class variables as static. When you define a data member as static it means there is only one single instance of it. This doesn't seem to be what you want to do here. Instead of private: static bool haslife; static int x; static int y; write: private: bool haslife; int x; ...
2,172,379
2,172,627
Get outline for NSGlyph
With Core Text it was possible to get the outline of a CGGlyph by CTFontCreatePathForGlyph(...). Now I'd like to port from Core Text to Cocoa's font engine, so the question is: Is there a way to get the outline for a NSGlyph?
Yes, you can use NSBezierPath's -appendBezierPathWithGlyph:inFont:. I'd like to add that you can use CoreText with Cocoa, too. So in that sense you don't have to port at all.
2,172,448
2,172,479
Common term for the "value-based" OR operator
Just a quick question printf("%d", 99 || 44) prints "1" in C print 99 || 44 prints "99" in perl There are two different kinds of evaluation. Does each one have a name? edit: i'm interested to know how this Perl evaluation is commonly called when compared to C. When you say "C example is X, and perl example is not X...
The C version uses || as the logical OR between the two values. Both 44 and 99 evaluate to true in C as they are not 0, so the result of an OR between them returns 1 (AKA true in C) In that particular perl snippet, || is the null-coalescing operator, an binary which evaluates to the second argument if the first is null...
2,172,621
2,172,631
cannot open shared object file: No such file or directory
I met the share library not found on the head node of a cluster with torch. I have built the library as well as specify the correct path of the library while compiling my own program "absurdity" by g++. So it looks strange to me. Any idea? Thanks and regards! [tim@user1 release]$ make ... ... g++ -pipe -W -Wall -...
Your LD_LIBRARY_PATH doesn't include the path to libsvmlight.so. $ export LD_LIBRARY_PATH=/home/tim/program_files/ICMCluster/svm_light/release/lib:$LD_LIBRARY_PATH
2,172,647
2,172,766
Template Metaprogramming - Difference Between Using Enum Hack and Static Const
I'm wondering what the difference is between using a static const and an enum hack when using template metaprogramming techniques. EX: (Fibonacci via TMP) template< int n > struct TMPFib { static const int val = TMPFib< n-1 >::val + TMPFib< n-2 >::val; }; template<> struct TMPFib< 1 > { static const int val = ...
Enums aren't lvals, static member values are and if passed by reference the template will be instanciated: void f(const int&); f(TMPFib<1>::value); If you want to do pure compile time calculations etc. this is an undesired side-effect. The main historic difference is that enums also work for compilers where in-class-i...
2,172,726
2,209,160
Are there any reasons why the StringPiece/StringRef idiom is not more popular?
From the documentation of the StringPiece class in Chromium's source code: // A string-like object that points to a sized piece of memory. // // Functions or methods may use const StringPiece& parameters to accept either // a "const char*" or a "string" value that will be implicitly converted to // a StringPiece. // ...
Because why bother? With copy elision and/or pass by reference, memory allocations for std::string can usually be avoided as well. The string situation in C++ is confusing enough as it is, without adding still more string classes. If the language was to be redesigned from scratch, or if backwards compatibility wasn't a...
2,172,879
2,172,900
in C++, how to use a singleton to ensure that each class has a unique integral ID?
I have a bunch of C++ classes. I want each class to have something like: static int unique_id; All instances of a same class should have the same unique_id; different classes should have different unique_id's. The simplest way to do this appears to be threading a singleton through the classes. However, I don't know w...
Have a class that increments it's ID on each creation. Then use that class as a static field in each object that is supposed to have an ID. class ID { int id; public: ID() { static int counter = 0; id = counter++; } int get_id() { return id; } }; class MyClass { static ID id; publ...
2,172,919
2,172,997
A C++ syntax question involving non trivial templating and friend declaration
The following code should be self explanatory. I have two questions regarding the used syntax (which is the syntax that must be used). I'll be forever grateful if you could provide me with answers for these presented questions. template <typename T> struct A { template <typename S> void f (const A<S> &s); ...
why isn't the syntax ... Why can't the syntax be ... What do you expect us to say? Whoever decided this syntax (mostly Stroustrup himself, AFAIK) thought their syntax better than yours. Which one is nicer or easier to remember I wouldn't know - but I do find theirs making more sense than yours. You're free to disagre...
2,172,943
2,172,948
Size of character ('a') in C/C++
What is the size of character in C and C++ ? As far as I know the size of char is 1 byte in both C and C++. In C: #include <stdio.h> int main() { printf("Size of char : %d\n", sizeof(char)); return 0; } In C++: #include <iostream> int main() { std::cout << "Size of char : " << sizeof(char) << "\n"; ret...
In C, the type of a character constant like 'a' is actually an int, with size of 4 (or some other implementation-dependent value). In C++, the type is char, with size of 1. This is one of many small differences between the two languages.
2,173,063
2,179,327
Drawing Collision on Screen
And here we are for another question. After the previous one, i finally completed the kDop system and everything related. (Hierarchycal tree of kDop, etc..) Everything works fine. Now i want to draw on screen the collision for debug purpose and to see the result of the work. (To see if the hierarchical choice i've done...
In general, each vertex is the intersection of three planes. Additionally, each vertex you want to draw needs to be on the correct side of all remaining planes. This may be an annoying combinatorial description of the problem, but with a kDop, at least it's a fixed-size problem... To get a bit more clever about it, y...
2,173,151
2,173,273
How to end line with QTextEdit
I'm trying to create QTextEdit with some text, and in this text I have end of line characters (\n), but it is not accepted in QTextEdit object (whole text is displayed without any breaks). Any reason why?
If you're using Qt 4.3 or later, then you can use setPlainText(const QString &text) You can turn off rich text editing with setAcceptRichText(bool accept) (Qt 4.1 or later)
2,173,177
2,173,188
try all or just what's necessary?
What is better coding practice: if I have to have a try/catch block shall I place everything (every initialization and so on) in this block or just those variables which may throw? Is there any difference between those two constructions? In example: Having: struct A { A(); int a; int* b; }; and late...
I think a good general principle is to make a try block as "narrow" as possible -- don't put in it things that you believe won't ever cause exceptions. That way, should you ever be wrong and have one of those "can't cause exception" parts actually do cause an exception, you won't be accidentally "swallowing" the aston...
2,173,256
2,173,303
Why don't I have setTextFormat in my QTextEdit?
Anyone have any Idea why I don't have this function (setTextFormat) in my QTextEdit class? Thanks in advance.
See this answer to your previous question. QTextEdit API changed in Qt4 QTextEdit docs for Qt 4.6
2,173,323
2,173,438
Calculating time by the C++ code
I know this question has been asked few times over SO but none of them is really helping me out, so asking again. I am using windows xp and running visual studio c++ 2008. All the code which i am looking is using time.h but i think may be its not working correctly here, because results are making me suspicious. So this...
Here is what I use to print time in milliseconds. void StartTimer( _int64 *pt1 ) { QueryPerformanceCounter( (LARGE_INTEGER*)pt1 ); } double StopTimer( _int64 t1 ) { _int64 t2, ldFreq; QueryPerformanceCounter( (LARGE_INTEGER*)&t2 ); QueryPerformanceFrequency( (LARGE_INTEGER*)&ldFreq ); return ((double)(...
2,173,342
2,173,372
C++ template class and template function
If I have one template class and template function like this template <class T> T getMax (T a, T b) { return (a>b?a:b); } template <class T> class GetMax { public: static T getMax(T a, T b) { return (a>b?a:b); } }; Why are these not valid? x=getMax(1, '2'); but these are va...
What should getMax(1, '2'); return? An int, or a char? Think about it :) You could write: template <class T1, class T2> T1 getMax (T1 a, T2 b) { return (a>b?a:b); } But note that you are explicitly returning type 1, what might not work in a case like getMax('1',1000) because 100 would be converted to char type, and...
2,173,368
2,173,387
fstream >> int failing?
Any idea why the following would fail? std::fstream i(L"C:/testlog.txt", std::ios::binary | std::ios::in); int test = 0; i >> test; fail() is returning true. The file exists and is opened. I checked i._Filebuffer._Myfile._ptr and it is pointer to a buffer of the file so I don't see why it is failing.
You're opening the file in binary mode. The extraction operators were meant to be used with text files. Simply leave out the std::ios::binary flag to open the file in text mode. If you actually do have a binary file, use the read() function instead. Edit: I tested it too, and indeed it seems to work. I got this from CP...
2,173,395
2,173,685
How to encode video?
I want to write a video encoding. What do I need to do?
Do you mean implement / invent a codec, or do you mean encode a video? For encoding a video, use libavcodec from ffmpeg. For implementing or developing a new codec, this is typically done over a series of years by a team of experts, and if you have to ask this general a question it may be a learning experience but woul...
2,173,570
2,173,895
Translate a code using pointer, to Assembly in Pascal - Delphi
I have this code below, and I want to translate it to ASM, to use in Delphi too. var FunctionAddressList: Array of Integer; type TFunction = function(parameter: Integer): Integer; cdecl; function Function(parameter: Integer): Integer; var ExternFunction: TFunction; begin ExternFunction := TFunction(Functi...
First test app to reproduce error: var FunctionAddressList: Array of Integer; function Bar(parameter: Integer): Integer; cdecl; begin ShowMessage('Bar '+IntToStr(parameter)); end; function Foo(parameter: Integer): Integer; cdecl; asm mov eax, FunctionAddressList jmp dword ptr [eax + 5 * 4] end; procedure TFo...
2,173,696
2,173,704
How to tell if you're compiling on Windows?
Something like: #ifdef WINDOWS // do stuff #endif
The _WIN32 is always defined on Windows platform, checkout the predefined macros.
2,173,746
2,173,764
How do I make this C++ object non-copyable?
See title. I have: class Foo { private: Foo(); public: static Foo* create(); } What need I do from here to make Foo un-copyable? Thanks!
class Foo { private: Foo(); Foo( const Foo& ); // non construction-copyable Foo& operator=( const Foo& ); // non copyable public: static Foo* create(); } If you're using boost, you can also inherit from noncopyable : http://www.boost.org/doc/libs/1_41_0/boost/noncopyable.hpp EDIT: C++11 versi...
2,173,771
2,175,515
printf inside CUDA __global__ function
I am currently writing a matrix multiplication on a GPU and would like to debug my code, but since I can not use printf inside a device function, is there something else I can do to see what is going on inside that function. This my current function: __global__ void MatrixMulKernel(Matrix Ad, Matrix Bd, Matrix Xd){ ...
EDIT To avoid misleading people, as M. Tibbits points out printf is available in any GPU of compute capability 2.0 and higher. END OF EDIT You have choices: Use a GPU debugger, i.e. cuda-gdb on Linux or Nexus on Windows Use cuprintf, which is available for registered developers (sign up here) Manually copy the data th...
2,173,804
2,173,814
[Windows] Net to Host Not Working
The value is 10240 or 2800 in hex. TOTAL_LENGTH is a unsigned short. 0028 in decimal is 40 which is what I am expecting (or is at least a reasonable value). Any ideas why I am getting a 0 instead of a 40? Thinking about reversing the bits myself but really don't want to. xD unsigned short total_length = ntohl(ipData->...
u_long WSAAPI ntohl( __in u_long netlong ); The result is a long, and you're assigning it to a short. Check if it doesn't get cut. Also, if it's a short, then why aren't you using ntohs?
2,173,995
2,174,041
C++ member function applied to object
I want to call member function by passing it as template parameter, without using boost is possible. Here is an example off what I tried to do, class object { void method(); } { object object_instance; ... apply<object:: method>(); ... template<class F> void apply() { F(object_instance); } // want to call object_inst...
Something like: struct foo { void bar(void) {} }; template <typename R, typename C> R apply(C& pObject, R (C::*pFunc)()) { return (pObject.*pFunc)(); } int main(void) { foo f; apply(f, &foo::bar); } this.
2,174,084
2,174,095
Good source to learn about the differences between ATI and NVIDIA in OpenGL rendering?
The more i learn about OpenGL, the more problems i find! All i need is a list of the most common problems between ATI/NVIDIA cards, with solutions. So where is this magical source?
Unfortunately try it and discuss it on the NeHe and OpenGL forums. There are no real official lists and the bugs and mis-implemented features differ from card-card and with operating system.
2,174,107
2,174,136
Good tools for Multi-threaded C++ debugging on MacOSX?
I recently switched form ubuntu to MacOSX. I also recently started heavily using multi threading. What good addons/alternatives are there to g++ for debugging multi-threaded apps on MacOSX? In particular, I'm interested in tools that let me "poke" around classes/structs; to follow pointers, expand members, show the val...
Valgrind. Especially Helgrind. It's not a GUI tool like you suggested, but it'll save you a hell of a lot of time.
2,174,267
2,174,317
Simple Win32 Trackbar
I have created a simple game using Win32 and gdi. I would like to have a track bar at the bottom that tracks a global variable. I'm just not sure how to add controls. How could I add a trackbar? I can imagine it would get created in the wm_create event.
Do you mean TrackBar or StatusBar? A StatusBar is normally located at the bottom of a window and displays informational messages about the application status, a TrackBar allows the user to select a value. Do you want to allow the user to select the value of your global variable or do you just want to display the curre...
2,174,300
2,175,718
function template overloading
Can anybody summarize the idea of function template overloading? What matters, template parameter or function parameter? What about the return value? For example, given a function template template<typename X, typename Y> void func(X x, Y y) {} what's the overloaded function template? 1) template<typename X> void fu...
Of that list only the second introduces ambiguity, because functions - regardless of whether they are templates - can't be overloaded based on return type. You can use the other two: template<typename X> void func(X x, int y); will be used if the second argument of the call is an int, e.g func("string", 10); template<...
2,174,519
2,174,542
How to include boost::thread in your C++ project?
What do I need to do to include boost::thread in my project? I have copied the whole thread folder to my working path (I wish to be able to run this on several computers) and I get fatal error C1083: Cannot open include file: 'boost/thread/detail/platform.hpp': No such file or directory From the line #include...
Unfortunately boost::thread is not a "header-only" library -- hence you need to have it compiled. There are basically two ways to go around it. you download a prebuilt install package from boostpro (assuming that you are on windows) -- https://sourceforge.net/projects/boost/files/boost-binaries/ you can build it your...
2,174,567
2,174,572
c++ how to ? function_x ( new object1 )
Hi i want to do the next instead of MyClass object; function_x (object); i want to function_x ( new object ); so what will be the structure of the MyClass to be able to do that .. if i just compiled it , it gives me a compile time error answer function_x (MyClass() ) New Edit thanks for the quick answers.. i di...
new is called on classes, not objects. And it returns a pointer, so unless function_x accepts a pointer, this is impossible. You can do this though: void function_y(MyClass* ptr) { // Do something } // Then call function_y(new MyClass); Note a few things about this: The default constructor of MyClass is called whe...
2,174,570
2,177,640
Qt: How to send an event to the operating/window system?
I want to create an event in one Qt application that can be picked up by a seperate Qt application running at the same time. The normal sendevent function requires you to name the object which will receive it but I can't use that, I want it to be like a keyboard press event which filters through any open programs in th...
Take a look at Inter-Process Communication in Qt. The most cross-platform friendly way is to use a socket. Shared memory is also an option, but for events I would recommend a socket that you can then attach slots to on the receiving side to handle it like a local event. Edit: Sorry I think i missed the real point wh...
2,174,584
2,406,769
Binding event to wxMenu instead of wxMenuItem
Im creating a dynamic MenuBar from xml file, and binding events to menu items using Connect(). Some menus does not have items inside, but needs to fire events. Is there a way to attach an event handler to a wxMenu using Connect()? *Im Using wxWidgets 2.8.8 & MS VC++ 6.0
Ive tried many things, but nothing worked out for me. As a quick answaer ill quote Vadim Zeitlin from wx-widgets list: No, you shouldn't associate commands directly to top level menus. This is discouraged under all systems and is not supported at all under some of them.
2,174,657
2,175,295
When are header-only libraries acceptable?
Personally, I quite like header-only libraries, but there are claims they cause code bloat due to over-inlining (as well as the other obvious problem of longer compile times). I was wondering, how much truth is there to these claims (the one about bloat)? Furthermore, are the costs 'justified'? (Obviously there are una...
I work for a company that has a "Middleware" department of its own to maintain a few hundreds of libraries that are commonly used by a great many teams. Despite being in the same company, we shy from header only approach and prefer to favor binary compability over performance because of the ease of maintenance. The gen...
2,174,768
2,182,269
Generating random UUIDs in Linux
I am stuck in a strange predicament. I need to generate UUIDs in my Linux program (which I distribute using RPMs). I do not want to add another dependency to my application by requiring the user to install libuuid (seems like libuuid isn't included in most Linux distros, like CentOS). Isn't there a standard Linux syste...
Thanks for all your comments! I went through each one, and here's what suited my requirement the best: What I needed was just plain time-based UUIDs which were generated from random numbers once for every user who installed the application. UUID version 4 as specified in RFC 4122 was exactly it. I went through a the a...
2,174,838
2,177,486
Is "var" in C# analagous to "size_t" in C?
I have gotten used to using size_t in my C++ code by way of C due to a professor's insistence and I was curious if 'var' in C# is the same sort of thing?
If you are asking whether the use of var is like size_t in that you don't actually need to use size_t, you can get away with an int, then yes, they are kind of similar in that respect. However, they differ in that size_t is about making your code more explicit, whilst var is about removing some redundant explicitness f...
2,174,881
2,174,903
Why have a pointer to a pointer (int **a)?
int **a = malloc2d(M, N) // dynamically allocates a 2D array What is the purpose of having int **a vice int *a. I understand that pointers are needed for dynamic allocation but why have a pointer to a pointer? For a 3-dimensional array would it be: int ***a ?
You need a pointer to a pointer for several reasons. In the example you gave, a double pointer is used to store the 2D array. A 2D array in C is treated as a 1D array whose elements are 1D arrays (the rows). For example, a 4x3 array of T (where "T" is some data type) may be declared by: "T mat[4][3]", and describ...
2,175,189
2,175,422
what are the OOP features which are not in java but c++ has those features?
Respected Sir! As i have not learnt java yet but most people say that C++ has more OOP features than Java, I would like to know that what are the features that c++ has and java doesn't. Please explain.
This might be controversial, but some authors say that using free functions might be more object oriented than writting methods for everything. So by those author's point of view, free functions in C++ make it more OO than Java (not having them). The explanation is that there are some operations that are not really per...
2,175,298
2,175,324
Allocate more processor cycles to my program
I've been working on win32, c,c++ for a while. I code on visual studio. Most of the time I see system idle process uses more cpu utilization. Is there a way to allocate more processor cycles to my program to run it faster? I understand there might be limitations from i/o, in those cases this question doesn't make any s...
If your program it the only program that has something to do (not wait for IO), its thread will always be assigned to a processor core. However, if you have a multi-core processor, and a single-threaded program, the CPU usage of your process displayed in the task manager will always be limited by 100/Ncores. For exampl...
2,175,302
2,175,312
Unique Numerical ID for a Templated Class using Function Address
So, this question has been asked before, but I wanted a question with some of those key words in the title. The issue is simple: How can I have a templated class, such that for each instance of the template - but not each instance of the class - there is a unique, numerical identifier? That is, a way to differentiate: ...
template<class T> class Base { public: static void classID(){} private: T* t; }; int main() { Base<int> foo; Base<int> foo2; Base<char> foo3; /* unsigned int i = reinterpret_cast<unsigned int>(Base<int>::classID); unsigned int ii = reinterpret_cast<unsigned int>(Base<char>::classID); ...
2,175,418
2,175,486
Quick way to fetch URL html contents with Qt?
I'm not interested in the QNetWork class and all it's callbacks, I want a static function or something where I can just: QString html = QHttpHelperThingy::fetch("http://blah.com"); Does such a thing exist?
I believe that this is the replacement path: http://doc.qt.io/archives/4.6/qnetworkaccessmanager.html, but QHttp will work throughout 4.x series.
2,175,445
2,175,553
effective C++ data structure to consider in this case
Greetings code-gurus! I am writing an algorithm that connects, for instance node_A of Region_A with node_D of Region_D. (node_A and node_D are just integers). There could be 100k+ such nodes. Assume that the line segment between A and D passes through a number of other regions, B, C, Z . There will be a maximum of 2...
You should try to group stuff together when you can. You can group the information on each region together with something like the following: class Region_Info { Region *ptr; int thickness; // Put other properties here. }; Then, you can more easily create a data structure for your line segment, maybe something l...
2,175,455
2,175,468
C++ My first template ever
Ok, which is the best to avoid ambiguity here? template <class T> inline void swap(T &a, T &b) { T c; c = a; a = b; b = c; } /* blah blah blah (inside of a function:) */ for (itv = vals.begin(); itv != vals.end(); ++itv) { if (at < (*itv)) { swap(at, (*itv)); } if (at % (*itv) == 0) atadd = false; } /* blah...
The problem is namespace std also contains swap() function and looks like you have using namespace std; somewhere earlier, so the compiler can't decide which swap() to use - yours from the global namespace or the one from namespace std. You need to prepend the call with "::" to explicitly tell the compiler to use your ...
2,175,665
2,178,062
CreateProcess, process do not terminate when redirecting std out/in/err
I'm trying to use CreateProcess to launch a powershell script from within my application. I've used the Microsoft example (http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx) to create the child process and redirect the standard out/in/err pipes. The only issue left to solve is why the child process (powersh...
Is your parent reading the child's stdout completely? If you don't read it all then I believe the child will hang. Also, if the script expects input you will have to write something to the child's stdin or else it will hang. You could attach windbg to the child and see where it is hanging; maybe it will give you an ...
2,175,808
2,176,433
boost::spirit composing grammars from grammars
I have figured out how to use spirit -- i.e., I have written a moderately complex grammar. I always take the approach of growing a program -- one subsystem at a time. I've written the data structures for a complex model which has 4 types at the highest level. I would like to use the grammar composed from rules approac...
simplified from an actual program, Qi should work the same as Karma. template<class Iter> struct subgrammar_1 : karma::grammar<Iter, ...> { ... } template<class Iter> struct top_level_grammar : karma::grammar<Iter, ...> { top_level_grammar() : top_level_grammar::base_type(start) { start %= r1 | r2;...
2,175,867
2,175,960
Can I add file in Visual Studio 2003 and make it point to an existing file in another project?
This is a question about using Visual Studio 2003. Sorry it is not strictly a programming question but it does affect my work in a rather annoying way. I have a solution with 3 different projects (let's say MyProgram, UnitTest and PerformanceTest), and there is a file (let's say myclass.h) which needs to be shared betw...
Try this - To create a link to an existing item: 1.In Solution Explorer, select the target project. 2.On the Project menu, select Add Existing Item. 3.In the Add Existing Item dialog box, locate and select the project item you want to link. 4.From the Open button drop-down list, select Add As Link. http://msdn.microsof...
2,176,040
2,178,453
How to create artificial nodes in QAbstractItemModel for QTreeView
my question is about Qt and its QAbstractItemModel. I have a map of strings and doubles (std::map<stringclass, double>) which I would like to present in a Qt widget. While I could use QTableView for that, I would like to exploit the fact that the keys of the map are of form "abc.def.ghi" where there can be multiple st...
I would parse the map and create a tree data structure based on it. Make sure you sync the model when you change the map. If this sync step gets too complicated you might want to hold your data in a tree structure from the start and convert to a map when necessary. Parsing the map on the fly in the model functions seem...
2,176,299
2,176,370
Core dump analysis using gdb
I have a couple of questions regarding core dumps. I have gdb on Windows, using Cygwin. What is the location of core dump file? Is it a.exe.stackdump file? (This is the only file that generated after crash) I read on other forums that the core dump file is named "core". But I don't see any file with name "core". What ...
You need to configure Cygwin to produce core dumps by including error_start=x:\path\to\dumper.exe in your CYGWIN environment variable (see here in section "dumper" for more information). If you didn't do this, you will only get a stacktrace -- which may also help you in diagnosing the problem, though. Start gdb as fo...
2,176,336
2,176,372
c++ Socket select and receive problem
Below is the code fragment I have issue with socket programing. Here after select call, If I do not put a sleep on line 9, on Windows XP, 1 byte is received on line 11 (instead 4 byte is sent from server as integer), when I check xmlSize, it is set to 0. Because iResult is 1, execution continues and on line 15 second r...
If this is a TCP socket, you shouldn't care. The socket delivers a stream, it's doesn't correspond in any way or fashion to the size of the original write()s to the other end. It could deliver a megabyte as one million 1-byte read()s, or as a single 1MB one, or any combination in between. If you depend on the size of t...
2,176,427
2,176,455
Comprehensive gnu make / gcc tutorial
I've just started learning C++ and I find it very hard to find short, comprehensive tutorials on how to use gnu make / gcc. Any ideas (please don't point me to the official gnu make tutorial, it's way too much in-depth for my purposes ;-)).
Check the book Managing Projects with GNU Make. The entire text of this book is available online. Part I of this book covers the basic concepts, which I think would help you get comfortable with GNU Make.
2,176,711
2,176,739
Sentinel while loop for C++
Can anyone tell me what is sentinel while loop in C++? Please give me an example using sentinel while loop.
A "sentinel" in this context is a special value used to indicate the end of a sequence. The most common sentinel is \0 at the end of strings. A "sentinel while loop" would typically have the form: while (Get(input) != Sentinel) { Process(input); }
2,176,798
2,176,811
C++ empty class or typedef
I'm currently using something like that in my code: class B : public A<C> { }; Wouldn't it be better to use a typedef? typedef A<C> B;
It depends. If you want A<C> and B to be distinct but related types, B should extend A<C>. If you want them to be identical, you should use a typedef. Can you provide any more context?
2,176,877
2,176,894
Sourceannotations.h ? C++
What is this errormessage in Visual Studio 2008 Error 1 error C2144: syntax error : '__w64 unsigned int' should be preceded by ';' c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h 19 Steg2_Labs I don't have any headerfiles made myself.
You are missing a semicolon somewhere before the "integral type" declaration. Since you say there aren't any other libraries included (written by you) than it must be in the current file and usualy the statement directly before the error line number.
2,176,930
2,176,955
C++ STL List calculate average
I have to correct some C++/STL code. Unfortunately I have very little C++ experience and know nothing about STL. Nevertheless I finished most of it, but the function below is still giving me problems: C++ source: double MyClass::CalculateAvg(const std::list<double> &list) { double avg = 0; std::list<int>::itera...
So, the first error is there: std::list<int>::iterator it; You define an iterator on a list of integers, and use it to iterate on a list of doubles. Also, an iterator can only be used on a non-constant list. You need a constant operator. You should write: std::list<double>::const_iterator it; At last, you forgot to r...
2,177,105
2,177,549
Windows Performance Analysis Tool usage as a profiler
I have an application written in c++ using visual studio 2005. The application has certain performance problems. I would like to explore where. I need to drill down in which classes/methods/lines the application spends most of the time. Can this be done with the WPA? If yes, can you, please give me a pointer to documen...
No, WPT leverages windows events, it would only help you diagnose a problem when Windows is the cause of your slow-down. You certainly won't get any diagnostics for your code. What you need is a real profiler. Good ones cost money. Check this thread for more advice.
2,177,209
2,177,254
Is it possible to pass a C ellipsis call through directly?
void printLine(const wchar_t* str, ...) { // have to do something to make it work wchar_t buffer[2048]; _snwprintf(buffer, 2047, ????); // work with buffer } printLine(L"%d", 123); I tried va_list vl; va_start(vl,str); and things like this but I didn't find a solution.
Here's a simple C code that does this, you will have to include stdarg.h for this to work. void panic(const char *fmt, ...){ char buf[50]; va_list argptr; /* Set up the variable argument list here */ va_start(argptr, fmt); /* Start up variable arguments */ vsprintf(buf, fmt, argptr); /* print the variab...
2,177,327
2,179,212
Container access and allocation through the same operator?
I have created a container for generic, weak-type data which is accessible through the subscript operator. The std::map container allows both data access and element insertion through the operator, whereas std::vector I think doesn't. What is the best (C++ style) way to proceed? Should I allow allocation through the su...
Separate insert method, definitely. The operator[] on std::map is just stupid and makes the code hard to read and debug. Also you can't access data from a const context if you're using a operator[] to insert (which will lead to un-const-cancer, the even-more evil cousin of const-cancer).
2,177,474
2,177,488
Visual Studio add-on to tag code segments?
I wonder if there exists any add-on for VS that can substitute/tag some lines of code with a descriptive text of my choice ? Ideally a function like the one below : bool CreateReportFiles(LPCTSTR fn_neighbours, ULONG nItems, ULONG* items) { // Read from file CFile cf_neighbours; if (!cf_neighbours.Open(fn_neighbour...
The region functionality does pretty much precisely what you describe, and is built into Visual Studio. The following will compress as you described: bool CreateReportFiles(LPCTSTR fn_neighbours, ULONG nItems, ULONG* items) { #pragma region ReadFile // Read from file CFile cf_neighbours; if (!cf_neighbours.Open(fn_...
2,177,619
2,177,631
Finding division by zero in a big project
Recently, our big project began crashing on unhandled division by zero. No recent code seems to contain any likely elements so it may be new data sets affecting old code. The problem is the code base is pretty big, and running on an embedded device with no comfortable debug access (debug is done by a lot of printf()s o...
Finding all of the divisions shouldn't be hard with a custom grep search. You can easily distinguish that usage from other usages of the / and % character in C++. Also, if you know what you are dividing, you could globally overload the / and % operator to have a __FILE__ and __LINE__ informing assertion. If using a mak...
2,177,731
2,177,757
How to get a basic preg_match_all replacement for std::string in C++?
with "basic" is meant: Only the operators "+" (->following..) and "|" (->or) are needed. Prototype: preg_match_all(std::string pattern, std::string subject, std::vector<std::string> &matches) Usage Example: std::vector<std::string> matches; std::string pattern, subject; subject = "Some text with a lots of foo foo and ...
You could rollup something using std::string::find, doing matches via a functor, and pushing the results onto a string vector. The way it's realized in boost is probably overkill for what you want -- you first would need to decompose the expression into lexems and then compile a state machine for parsing the given rege...