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,251,305
3,251,650
How do I use SSE(1,2,3,4) optimizations?
I'm wondering if simply compiling my msvc project with sse/sse2 will have any effect. I do for example vector normalization and dot product but I do these wth math, not any specific function. Is there like sse_dot() and sse_normalize() that I should be using to actualyy take advantage, or will the compiler know? Thanks...
As I understand it, using the sse2 compiler option will result in the compiler using the scalar not vector sse2 instructions in place of normal fpu code. I don't think it will do any vectorisation. The sse2 scalar stuff is quicker than fpu for sure. To use the vector unit you need to use either intrinsics directly ( xm...
3,251,307
3,251,368
What's the best workflow to keep cpp files and header files in sync?
I'm trying to learn C++ for Qt development, and I'm a little scared of header files. What I'd like to know is, what's the best workflow for keeping *.cpp and *.h files synched? For example, is the norm to write the class file and then copy the relevant info over to the header? Sorry if this doesn't make any sense...I'...
For example, is the norm to write the class file and then copy the relevant info over to the header? While there is no single standard approach, its usually a good idea to: first think about the public interface put that in the header implement in the source file accordingly update the header if needed Jumping str...
3,251,336
3,251,366
Memory allocation of identical structs
So I was teaching my friend about pointers. While doing so, I noticed that the address of two identical structs are exactly back-to-back. struct Foo { int a; }; struct Bar { int b; }; Which allowed me to do this: Foo foo; foo.a = 100; Bar bar; bar.b = 100; Foo *pFoo = &foo; Bar *pBar = &bar; (pFoo+1)->a = 2...
No, not necessarily. It is possible that some architectures/compilers will align structures on boundaries such that there are different spacings between structs in an array and structs on the call stack. You're allocating on the call stack and treating them as a contiguous array, that's an unreliable assumption.
3,251,465
3,251,503
Correct implementation of Boyer Moore algorithm
I tried to use several implementations, but all of them had bugs. Search at SO gave me http://www-igm.univ-mlv.fr/~lecroq/string/node14.html - looks nice, but this implementation gave me wrong results - sometimes it doesn't found a string. I spent couple hours to find the bug. Following line looks fine: j += MAX(bmGs[i...
char isn't definitively signed or unsigned - it's unspecified, and left up to the implementation to define. If the algorithm depends on char being unsigned, then it should explicitly cast the input pointers to unsigned char (which is how the C standard library string handling functions are defined to work - all compari...
3,251,506
3,251,531
Compiling into executable file
I am currently writing a programming language in C/C++ as an exercise (but mostly for fun). At the moment it compiles into a list of commands that are then executed (kind of like a low-level API). Its working fantastically, however, I think it would be more exciting if instead of having a interpreter executable, havi...
You could consider writing a frontend for LLVM (tutorial) or GCC (article from linux journal) - if thats still fun for you is a different question.
3,251,667
3,252,184
Find out which functions were inlined
When compiling C++ with GCC 4.4 or MSVC is it possible to get the compiler to emit messages when a function is inlined?
With g++, I don't think you can make g++ report that, but you can examine the resulting binary with any tool that shows symbols, nm for example: #include <iostream> struct T { void print() const; }; void T::print() const { std::cout << " test\n" ; } int main() { T t; t.print(); } ~ $ g++ -O3 -...
3,251,790
3,251,888
Getting "execute" permission for an area of memory
I am using C++, and would like to get the permission to execute on an area of memory. Is there a way I can do this? Right now when I just try to execute it, I get an access violation error.
On Windows the function is VirtualProtect, you'll want to pass in PAGE_EXECUTE_READWRITE to get execute permission. By default Windows does not allow memory. It's called Data Execute Prevention (DEP).
3,251,930
3,251,955
*(c++) operator order
What precedence rules apply in parsing this expression: *(c++); // c is a pointer. Thank you. well, I tried the following x = *c; c++; x = (*c++); x = *(c++); They appear to be equivalent
the ++ operator has not so much to do with precedence, but tells to increment only after evaluation. So *c will be "returned" and then c will be incremented. Please don't confuse precedence with order of execution!
3,251,983
3,256,743
What is the syntax for an array type?
Is it type[]? For example, could I have T<int[]>; for some template T.
There are two syntaxes to denote array types. The first is the type-id syntax and is used everywhere where the language expects a compile time type, which looks like: T[constant-expression] T[] This specifies an array type that, in the first form, has a number of elements given by an integer constant expression (means...
3,252,238
3,252,277
Light weight container around const char* & length without copying the data
I have a underlying API that passes a const char* and a length: foo(const char* data, const uint32_t len); I'd like to wrap this data/length in a light weight container that can be iterated and has the ability to be randomly accessed but not make a copy (e.g. like a vector). What is the best way to achieve this? The c...
It would be easy to make such a class. Something like this: template <class T> class array_ref { public: // makes it work with iterator traits.. typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef T* iterator; ...
3,252,248
3,252,603
Calling member functions from DLL (AI library for games)
My problem is this: I am trying to implement a C++ library which can call functions in the base EXE. I am trying to have a minimum amount of code on the EXE side to get the functionality to work. At the moment I have DLL-side entities which are created by DLL function calls. These entities hold a container of "actions"...
What you want is boost::bind and boost::function. The dll side map would have boost::functions instead of function pointers. The client would pass a bound object using boost::bind which could be anything you want. DLL Side: typedef boost::function<void ()> CallbackFunctionType; CallbackFunctionType gCallback; void Se...
3,252,410
3,252,443
Trouble with 'extern' Keyword
I have a set of global variables and a method in a cpp file. int a; int b; int c; void DoStuff() { } in the header file I have declared them explicitly with the extern keyword. My problem is when I include the header file in another C++ file, I can't use the external variables and the method. It's giving a linker ...
Try this Define those variables inside your header instead of just declaring them. extern int x; is just a declaration(not a definition) Simple example a.cpp int a,b,c; //definition void doStuff(){ } b.cpp extern int a,b,c; //extern keyword is mandatory void doStuff(); //extern keyword is optional because fun...
3,252,762
3,252,841
Porting C++ code to Silverlight
I have C++ application which has UI developed using MFC, does some networking using sockets (using boost libraries) and some image processing. I want to move this application into Silvelight framework (I can use 4.0 if required) so that it can be used over the internet easily. Here I want to move all parts (UI + networ...
Silverlight 4 supports COM when running in trusted mode. So, tecnically you could have Silverlight call your c++ library using COM. The main problem I see is on deployment and I don't think it's a good idea. Also, remember that Silverlight can run on Macs but COM is Windows only. What you could do is to have the image...
3,252,909
3,252,933
Is C++ name mangling (decoration) deterministic?
I hope to LoadLibrary on an unmanaged C++ DLL with managed code, and then call GetProcAddress on extern functions which have been mangled. My question is are the mangled names you get from a C++ compiler deterministic? That is: Will the name always by converted to the same mangled name, if the original's signature hasn...
It isn't specified by the standard, and has certainly changed between versions of the same compiler in my experience, though it has to be deterministic over some fixed set of circumstances, because otherwise there would be no way to link two separately compiled modules. If you're using GetProcAddress, it would be far c...
3,253,046
3,253,065
Implementing the clrscr() function to understand its working
I am trying to make the copies of the builtin functions and adding a x to their name so i can understand each functions working.While writing a function for clrscr() i am confused about how it works.Does it use 2 nested loops and print (" ") i.e space all over the screen or it prints("\n") over the screen?Or what? I tr...
clrscr() implementation may depend on the environment your console application runs. Usually it sends the ClearScreen control character (0x0C) to the console driver, that actually clears the screen. The driver knows about character space to clear as well as all attributes (blink, underline,...) to reset. If you dont w...
3,253,107
3,255,534
How to rotate monochrome images in GDI+
I am trying to rotate a monochrome Bitmap in GDI+ using RotateFlip method. When i try to rotate it by 90/270 I get a wrong image or the application crashes. But when I try to rotate it by 180 degrees it works fine. Hence I am now rotating all monochrome bitmaps twice through 180 and then rotating it again by the angle ...
protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Matrix m = new Matrix(); Bitmap bmp = new Bitmap("myfile"); m.Rotate(30); e.Graphics.Transform = m; e.Graphics.DrawImageUnscaled(bmp);
3,253,246
3,253,462
What is good way to maintain versions in a C++ project?
We have a C++ project, which has hundreds of SVN revisions every month. Sometimes we need to increment a minor digit in a version number, changing it from, say, 1.6 to 1.7. We do it once per month approximately. What is a correct approach to do it? We want to save/maintain information about changes made in every new ve...
For the 'release note' tracking, I suggest using some external tool to track tasks. You can assign functionalities and in many cases associate issue numbers with specific subversion commits. I have used ClearQuest and Jira for this in the past but there are opensource/free tools out there you can try. If you decide to ...
3,253,349
3,253,371
code from hackers delight
/* Converts the unsigned integer k to binary character form with a blank after every fourth digit. Result is in string s of length 39. Caution: If you want to save the string, you must move it. This is intended for use with printf, and you can have only one reference to this in each printf statement. */ char * binar...
You're throwing away the return value of the function binary : *binary(k); binary returns a char * which is (as the documentation says) "intended for use with printf", but you aren't doing anything with this string. Your program 'returns' 0 because that's what you're explicitly returning with your last line of code! T...
3,253,590
3,253,662
What is the meaning of this code
I found following code in one of the frameworks we are using, if (nValue + 0.01 > nLimit) nValue = nValue - 0.01; if (((nValue+1) / (int)(nValue+1)) == 1) sprintf(szValue, "%0.0f", nValue); else sprintf(szValue, "%0.2f", nValue); what is the meaning of this code
I'd suspect that the first part is a mistaken attempt to ensure nValue does not exceed nLimit. It possibly should be if (nValue + 0.01 > nLimit) nValue = nLimit - 0.01; In other words, if nValue is closer than 0.01 to the limit make it 0.01 less than the limit To explain how the second part works, it involves divi...
3,253,866
3,254,015
What's the clue to make stringstream write binary?
What I'm trying to do is, make the class message serialize and deserialize it's self. Not into or from a file, but into or from a binary sequence as a string or cstring. Message.h: class Message { private: int message_id; int sender_id; std::string sender_data; Message (); public: Message (int i...
Generally you serialize an object by serializing all it's data-members. Hence this will not work as expected: out_stream.write((char *)this, sizeof(*this)); This does not serialize data dynamically allocated data. If you have a lot of serialization/deserialization to do, take a look at Boost.Serialization. Even if you...
3,254,020
3,266,131
BDM elf file vs normal elf file
Whats the advantage that the BDM ELF file has over the normal ELF file in terms of memory used? I know the following things about both: BDM ELF file could be used for debugging through any debugger tools like Trace32 by plugging in JTAG. The normal ELF file also can be used for debugging purpose, provided we have the ...
OK, I'll try again: How is BDM ELF file content distributed among the Trace32 debugger and the ECM memory? The ELF file can hold debugging symbol information (relating memory locations and registers to functions and variables), which the trace32 uses to help you debug. This symbol information is held in trace32 and ...
3,254,148
3,254,269
Strange words appearing during compilation of Application
I am having a service written in C++ and i use VC++ 6.0. When i build this service i get a strange message as shown (The letter 'T'coming during compilation). Though it does not cause any problem, i would like to know why this message occurs. Compiling... SerString.cpp SerSwitcher.cpp Smtp.cpp SysConfigBlob.cpp T T Tra...
Perhaps this explains it? Try to look for #warning T or #pragma message ("T") inside your code / headers.
3,254,427
3,255,762
Are tuples of tuples allowed?
I'm currently working on a class with a lot of templates and being able to build tuples of tuples would make it a lot easier But I tried this simple code in MSVC++ 2010: #include <tuple> void main() { auto x = std::make_tuple(std::make_tuple(5, true)); } And I get a compilation error. The same problem happens if...
More data points: If we use std::tr1::tuple and explicitly state the type instead of using auto, then Visual C++ 2008 compiles the code without error. Trying to compile that same code with Visual C++ 2010 results in the error you are seeing. If we use boost::tuple an explicitly state the type instead of using auto, t...
3,254,491
3,256,318
C++ Undefined Type Error
Dear all, i have two classes which are computer and floppy disk. When i put #include "FloppyDisk.h" #include "Computer.h" in main, then compiler generates error of computer undeclared When i #include "Computer.h" #include "FloppyDisk.h" in main, then compiler generates error of floppy disk undeclared. What is the...
Are you using the same header include guard in each file, e.g.: #ifndef MY_INCLUDE_GUARD #define MY_INCLUDE_GUARD // blah blah #endif The MY_INCLUDE_GUARD needs to be a unique name in each header.
3,254,521
3,254,640
In how many ways we can take input values in C++?
How to take input values in C++, in how many ways we can take input values.? Please describe in brief with small examples
For console application you have two standard ways: Argument values. User input.
3,254,570
3,254,603
Appending pointers to QList
I need to insert pointers of classes (inherited from QObject) into a QList. I know that the following syntax can be used: .h QList<MyObject*> list; .cpp list.append(new MyObject("first", 1)); list.append(new MyObject("second", 2)); ... and then free memory: if(!list.isEmpty()) { qDeleteAll(list); list.clear()...
if you take care of "obj" (the allocated but not initialized instance) in the "// handle error" case, your code is ok.
3,254,652
3,720,560
Several ways of placing an image in a QTextEdit
I think this is a very simple question, but when I copy an image I can't paste it in a QTextEdit? Paste is inactive! Also I would like to know how to drag-and-drop a picture. BTW I use the following code in order to insert a picture into a QTextEdit: QTextEdit *textEditor = new QTextEdit(0); QTextDocumentFragment fragm...
The second way is this: void TextEdit::insertImage() { QString file = QFileDialog::getOpenFileName(this, tr("Select an image"), ".", tr("Bitmap Files (*.bmp)\n" "JPEG (*.jpg *jpeg)\n" "GIF (*.gif)\n" ...
3,254,664
3,573,467
Windows Mobile 6.5 Change the camera focus
I have a project to scan some QR-code or bar-code with camera on windows mobile. (phone x01t) Programing in C++ and using DirectShow. Tired to change focus with IAMCameraControl interface, but return the error like "...request is not supported". Are there any way else? Thanks
Most (if not all) Windows Mobile phones I've used so far used custom camera drivers, which means OEMs decide which functionalities to implement/support. IAMCameraControl is most likely not one of them. However, you might want to look for OEM-specific SDKs. For instance, Samsung provides custom APIs enabling to change s...
3,254,669
4,438,846
How to implement QTextDocument serialization
This question I have asked before and just got answer that there is an open bug for this. But this is a really required feature and, I guess, each Qt programmer who programmes a more or less serious application, it is quite probable that there is used a QTextEdit and the data is inserted in QTextEdit is serialized and ...
See here: How to serialize and deserialize rich text in QTextEdit?
3,254,788
3,254,949
How Visitor Pattern avoid downcasting
can anyone show example code before and after to avoid down casting for visitor pattern code ? Thanks.
A bare, minimalistic example. Before class Base {}; class Derived1 : public Base {}; class Derived2 : public Base {}; // Some arbitrary function that handles Base. void Handle(Base& obj) { if (...type is Derived1...) { Derived1& d1 = static_cast<Derived1&>(base); std::printf("Handling Derived1\n");...
3,254,834
3,255,355
How can I find a rare bug that seems to only occur in release builds?
I have a fairly large solution that occasionally crashes. Sadly, these crashes appear to only occur in release build. When I attach the debugger upon crashing, I get the message: "No symbols are loaded for any call stack frame. The source code cannot be displayed" This makes it quite hard to find the cause of the...
Sounds to me like that stack frame was blown. Trivial to do with a buffer overflow, just copy a large string in a small char[] for example. That wipes out the return address. The code just keeps running until the return, then bombs when it pops a bad address off the stack. Or worse, if the address happens to be val...
3,254,937
3,254,969
Creating objects of class through its name stored in a string?
Can I create an object of a class at runtime, by extracting the class name stored in a string? eg: I want to create and object of class QButton like QString strClassName = "QButton"; QButton *pBtn = new strClassName(); I want to read an xml file of all the controls and instantiate them at runtime using this way.
Maybe you are looking for the functionality provided by QUiLoader?
3,255,074
3,255,133
How to process jpg images with c/c++ most easily?
I want to iterate over each pixel color in a jpg format image, which library should I refer to to do this so that the code can be as short as possible?
I can think of either ImageMagick or CImg. Here is a CImg tutorial for you. They abstract away a lot of the decompression details and just give you a grid to work with. If you go with CImg, you only need to use the data call. You can probably do something like: CImg<unsigned char> src("image.jpg"); int width = src.w...
3,255,094
3,255,201
Minimum DirectX 9.0c version and how to check for it
Our Windows C++ Ogre-based game is nearing completion. Before we publicly release it, we have to solve this matter : Ogre crashes on many test-computers if they are not updated to the latest Dx9.0c version. All these computers already had 9.0c installed, but that must have been an older OS-pre-installed sub-version, he...
The 1st questions is : how can I ensure that a user has the correct 9.0c version so that the game doesn't crash on the user's face, but instead show a message like "Go get the latest 9.0c version from there...."? The best idea is to update/install DirectX silently from Game Installer. Along with other required system...
3,255,096
3,255,136
Why syntax error occurs when a void function is checked in IF statement
What will be the output if I write In C++ if(5) will be executed without any problem but not in C# same way will it be able to run. if(func()){} //in C# it doesn't runs Why how does C# treats void and how in Turbo C++ void func() { return; } if(null==null){}//runs in C# EDIT if(printf("Hi"){} //will run and enter i...
In C and C++ there is an implicit conversion of int , pointers and most other types to bool. The designers of C# elected not to have that, for clarity. So with int i = 1; int* P = null; if (i && p) { } // OK in C++ if (i != 0 && p != null) { } // OK in C++ and C#
3,255,339
3,255,378
C++ basic template question
I'm slightly confused with template specialization. I have classes Vector2, Vector3 which have operator+= in it (which are defined the following way). Vector2& operator+=(const Vector2& v) { x() += v.x(), y() += v.y(); return *this; } Now I want to add the generic addition behaviour and say somethi...
If the specialisation is in a header file, then you need to declare it inline to allow it to be included in more than one compilation unit. Note that you don't actually need a template specialisation here; a simple overload will do the same thing.
3,255,663
3,256,477
How to Set text color in OpenGl
I am new to openGL and wanted to set the text color tried the glColor3f function but it changes the drawing color as i only want to change the text color what should i do?
You could push the current colour onto the attribute stack, change the colour, draw the text, and then pop the stack to restore the original colour: glPushAttrib(GL_CURRENT_BIT); glColor3f(...); // Draw your text glPopAttrib(); // This sets the colour back to its original value
3,255,671
3,255,686
How can I make an object construct itself at a particular location in memory?
Possible Duplicate: Create new C++ object at specific memory address? I am writing what is essentially an object pool allocator, which will allocate a single class. I am allocating just enough memory to fit the objects that I need, and I am passing out pointers to spaces inside. Now my question is this: Once I have...
You use placement new. Like so: new( pointer ) MyClass();
3,255,899
3,255,955
Why are there WSA pendants for socket(), connect(), send() and so on, but not for closesocket()?
I'm going to try to explain what I mean using a few examples: socket() -> WSASocket() connect() -> WSAConnect() send() -> WSASend() sendto() -> WSASendTo() recv() -> WSARecv() recvfrom() -> WSARecvFrom() ... closesocket() -> WSA???() This is nothing that matters much, but is still something that gives me a splitting ...
closesocket is only available on Windows, I'm not sure why they didn't follow the WSA convention there though. If it really bothers you though you can make your own wrapper that calls closesocket. As mentioned in WSASocket a call to closesocket should be made.
3,255,962
3,256,251
Translating const strings in structure initializers
I'm working with a large code base which uses const strings in structure initializers. I'm trying to translate these strings via GNU gettext with a minimal amount of time. Is there some sort of conversion operator I can add to default_value which will allow Case #1 to work? #include <cstring> template<int N> struct fi...
What about direct conversion to data1? .. operator data1() const { data1 ret; std::strncpy(ret.string, text, sizeof(ret.string)); ret.string[sizeof(ret.string)] = 0; return ret; } .. and then: .. data1 d1 = default_value(translate("Hello")); // should work now... ..
3,255,971
3,255,988
method declared in struct in C++ (STL)
I'm trying to understand the syntax used in STL for a class. Our teacher pointed us to this website (http://www.sgi.com/tech/stl/Map.html) where I copied the code below: struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; int main() { map<const char*, int...
In C++, a struct is really just a class whose default access specifier is public and which inherits publicly by default. In other words, struct ltstr { // ... }; is equivalent to class ltstr { public: // ... }; If you want to, you can make parts of your struct protected or private, too. The reason that struct...
3,256,039
3,256,121
Cross-platform svn management (Makefiles & Visual Studio)
I'm working on a little game called freegemas, it's an open source version of the classic Bejeweled written in C++ and using gosu as the graphic API. I've been developing it under Ubuntu Linux as usual, but the other day I wanted to give it a try and I compiled it on Windows using Visual Studio 2005 (which I had never ...
You could just keep the project files in a seperate directory "winbuild" or similar. Still, to maintain them would require manual interaction (ie adding every new file manually). The only files you would need to upload to svn are the *.vcproj (for MSVC 2005/2008) and *.vcxproj (MSVC 2010). Alternatively, you could opt ...
3,256,045
3,256,223
How to exclude certain #include directives from C++ stream?
I have this C++ file (let's call it main.cpp): #include <string> #include "main.y.c" void f(const std::string& s) { yy_switch_to_buffer(yy_scan_string(s.c_str())); yyparse(); } The file depends on main.y.c, which has to be generated beforehand by means of bison util. In other words, I can't compile main.c file if ...
You can indicate in your makefile that main.c depends on main.y.c so that it'll run the bison process before it tries to compile main.c. As an alternative (which I think is probably not what you want to do) is that you can have your makefile pass a macro to the compiler to indicate whether or not main.y.c exists and us...
3,256,192
3,256,246
Complex initialization of const fields
Consider a class like this one: class MyReferenceClass { public: MyReferenceClass(); const double ImportantConstant1; const double ImportantConstant2; const double ImportantConstant3; private: void ComputeImportantConstants(double *out_const1, double *out_const2, double *out_const3); } There is a r...
Why can't you do: MyReferenceClass ComputeImportantConstants(){ //stuff to compute return MyReferenceClass( const1, const2, const3 ); } MyReferenceClass{ public: MyReferenceClass(double _1, double _2, double _3) : m_Const1(_1), m_Const2(_2), m_Const3(_3){} double getImportantC...
3,256,198
3,256,243
Does usleep create thread cancellation point?
According to the Linux manpages, only the following functions are thread cancellation points: pthread_join, pthread_cond_wait, pthread_cond_timedwait, pthread_testcancel, sem_wait, sigwait. In my test program, thread exits on usleep. Thread function: void* ThreadFunction(void* arg) { int n = 0; pthread_setcan...
The complete list of cancellation points and optional cancellation points is available in the POSIX spec: http://opengroup.org/onlinepubs/007908775/xsh/threads.html usleep() is a mandatory cancellation point
3,256,428
3,256,474
Can I use a preprocessor variable in #include directive?
This is what I'm trying to do: $ c++ -D GENERATED=build/generated-content main.cpp My main.cpp file: #include "GENERATED/header.h" void f() { /* something */ } Currently this code fails to compile. How should I fix it? And whether it's possible at all?
It seems you want to use different headers depending on some "compilation profile". Instead of the -Dsolution, I would rather suggest using the -I directive to specify the include directories. Given you have the following file tree: / debug/ header.h release/ header.h main.cpp: #include "header.h" /* some...
3,256,641
3,256,683
GCC equivalent to VC's floating point model switch?
Does GCC have an equivalent compiler switch to VC's floating point model switch (/fp)? In particular, my application benefits from compiling with /fp:fast and precision is not a big deal, how should I compile it with GCC?
Try -ffast-math. On gcc 4.4.1, this turns on: -fno-math-errno - Don't set errno for single instruction math functions. -funsafe-math-optimizations - Assume arguments and result of math operations are valid, and potentially violate standards -ffinite-math-only - Assume arguments and results are finite. -fno-rounding-m...
3,256,740
3,256,759
Variadic C++ function doesn't work when fetching arguments of type float
I have a variadic template function: template<typename T, typename ArgType> vector<T> createVector(const int count, ...) { vector<T> values; va_list vl; va_start(vl, count); for (int i=0; i < count; ++i) { T value = static_cast<T>(va_arg(vl, ArgType)); values.push_back(value); } va_end(vl); retu...
Floating point values are passed as doubles when passed to variadic functions, just as integers small than int are passed as int.
3,256,910
3,256,930
assign elements in vector declared with new. C++
I am trying to use a large 2D vector which I want to allocate with new (because it is large). if I say: vector< vector<int> > bob; bob = vector< vector<int> >(16, vector<int>(1<<12,0)); bob[5][5] = 777; it works. But if I say: std::vector< std::vector<int> > *mary; mary = new vector< vector<int> >(16, vector<int>(1<<1...
If mary is a pointer then you have to dereference it before applying the subscript operator: (*mary)[5][5] = 777; The parentheses are required because the subscript has higher precedence than the dereference.
3,256,998
3,257,018
C++ void type - how?
typedef void(Object Sender) TNotifyEvent; This is what I'm trying to do from Delphi to C++, but it fails to compile with 'type int unexpected'. The result should be something I can use like that: void abcd(Object Sender){ //some code } void main{ TNotifyEvent ne = abcd; } How do I make such type(of type void)? ...
If what you want is to define the type of a function that takes an Object as parameter and returns nothing, the syntax would be: typedef void TNotifyEvent( Object Sender ); EDIT, as answer to the comment. Yes, you can define the type of a function, and that type can later be used in different contexts with different m...
3,257,062
3,257,142
How to use Eigen, the C++ template library for linear algebra?
I have an image processing algorithm which makes of matrices, I have my own matrix operation codes (Multiplication, Inverse...) with me. But the processor I use is ARM Cortex-A8 processor, which has NEON co-processor for vectorization, as matrix operations are ideal cases for SIMD operations, I asked the compiler (-mfp...
The USING_PART_OF_NAMESPACE_EIGEN macro was removed in Eigen 3. Instead, simply use using namespace Eigen; Apparently, the tutorial is outdated.
3,257,116
3,295,486
JNI method returns old data
I've spent whole day on this problem and still have no idea how to solve it. Here is the simplified code JAVA class javaclass{ private volatile boolean isTerminated; public void javamethod() { log.logInfo("java :"+isTerminated()); } public int isTerminated() { return (isTerminated) ? 1 : 0; } pu...
I would suggest doing all the synchronization in one language or the other. It's looking like "volatile" isn't being respected across the boundary for some reason. Something like: public doJob() { while(!isTerminated) executeNative(); }
3,257,146
3,257,552
Class method with number of arguments specified by integer template parameter
Was not exactly sure how to phrase this question or what to search on so if this is the same as another question please close and redirect to the appropriate question. Suppose template<typename Type, int Size> class vector { Type data[Size]; } Is it possible to replace a constructor which takes Size number of argume...
In C++0x you have template typedef finally available! Disclaimer: nothing has been compiled... From Wikipedia's article: template< typename second> using TypedefName = SomeType<OtherType, second, 5>; which in your case would yield template <class Type> using vector3 = vector<Type, 3>; I can't tell you how much I crav...
3,257,393
3,257,590
Is it legal/well-defined C++ to call a non-static method that doesn't access members through a null pointer?
I came across the following code recently: class Foo { public: void bar(); // .. other stuff }; void Foo::bar() { if(!this) { // .. do some stuff without accessing any data members return; } // .. do normal actions using data members } The code compiles because in C++ methods are ...
This will probably work on most systems, but it is Undefined Behaviour. Quoth the Standard: 5.2.5.3 If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2 [...] And: 5.2.5.1 A postfix expression followed by a dot . or an arrow ->, optionally followed by the...
3,257,430
3,257,666
Do you get Debug Assertions under C++ when no CRT is installed?
When you have a Debug version of a C++ program running on an OS that has no VS or CRT installed, will you still get Debug Assertion error boxes? The ones that say "Debug Assert Failed!". Or will you only get them when the machine has certain components, such as CRT or Visual Studio installed?
If you can get it to run, yes. Compiling with /MDd (the default) requires distributing the debug version of the dynamic CRT. It is not a redistributable component, shipping it anyway is a license violation. You could get around it by compiling with /MTd. Of course, your user will have no idea what "Debug assertion f...
3,257,453
3,257,502
c++ ternary operator
So I ran into something interesting that I didn't realize about the ternary operator (at least in Visual C++ 98-2010). As pointed out in http://msdn.microsoft.com/en-us/library/e4213hs1(VS.71).aspx if both the expression and conditional-expression are l-values the result is an l-value. Of course normally in c/c++ you'...
A) Yes, this is part of the standard. B) It's not widely realized, though it may be here on SO. There's a reason it was voted the #1 hidden feature of C++: Hidden Features of C++?. C) No comment. :) Personally, I recommend steering clear of using this feature. It is a lot less intuitive than using if/else statements,...
3,257,465
3,257,515
Invalid use of List Iterator in c++
int num = 0; list::iterator it; for(it = binary.const_iterator; it !=binary.end(); ++it) { if(*it == '1') { abc.push_back(copyoflist.at(num)); } num++; } Here binary is defined as list binary; copyoflist is a char type vector. I am getting this error: invalid use of 'std::list >:...
const_iterator is a type, not a property. You would use it like this: list<char>::const_iterator it; for(it = binary.begin(); it != binary.end(); ++it)
3,257,584
3,257,671
O* p = new O[5]; What does p point to?
To the first O of the array?
Exactly. *p and p[0] are the same. Here are some neat features you want to know: "Pointer notation" generally refers to using the 'dereference' (or 'indirection') operator "Array notation" generally refers to using the brackets and offset value You can represent an address in memory using either interchangeably: *p ...
3,257,610
3,257,816
How can I catch my custom exception with Boost.Test?
When I'm testing my C++ class with Boost.Test and my custom exceptions are thrown (they are instances of my class), this is the message I see in log: unknown location:0: fatal error in "testMethod": unknown type It's very un-informative and I don't know how to teach Boost.Test to convert my exception to string and dis...
I believe it would work if your custom exception class inherited from std::exception.
3,257,687
3,257,759
Correct way to initialize array of boost::scoped_ptr?
I have a class with an array of scoped pointers to objects which do NOT have a default constructor. The only way I've found to "initialise" them is using swap() like this: class Bar { Bar(char * message) {}; } class Foo { boost::scoped_ptr<Bar> arr[2]; Foo() { arr[0].swap(boost::scoped_ptr<Bar>( new Bar(...
arr[0].reset(new Bar("ABC")); arr[1].reset(new Bar("DEF"));
3,257,707
3,257,870
Why is programming with objects not considered procedural?
Even though OOP uses objects and data encapsulation, the code still writes out like a procedure. So what makes OOP loose the procedural label? Is it just because it is considered "high-level"? Thank You.
It's not that Object-orient Programming is "non-Procedural"; it's just that the code we call "Procedural" is not Object-oriented (and not Functional and probably not a couple others) It's not so much an either-or case, but a slow gradiate: Spaghetti code -> Structured Code -> Object-oriented code -> Component code. (UP...
3,257,837
3,257,908
c++ search text n boolean mode
basically have two questions. 1. Is there a c++ library that would do full text boolean search just like in mysql. E.g., Let's say I have: string text = "this is my phrase keywords test with boolean query."; string booleanQuery = "\"my phrase\" boolean -test -\"keywords test\" OR "; booleanQuery += "\"boolean s...
TR1 has a regex class (derived from Boost::regex). It's not quite like you've used above, but reasonably close. Boost::phoenix and Boost::Spirit also provide similar capabilities, but for a first attempt the Boost/TR1 regex class is probably a better choice.
3,257,890
3,257,953
How to fix the syntax in this code rife with templates?
The following code template<typename T, typename U> class Alpha { public: template<typename V> void foo() {} }; template<typename T, typename U> class Beta { public: Alpha<T, U> alpha; void arf(); }; template<typename T, typename U> void Beta<T, U>::arf() { alpha.foo<int>(); } int main() { Beta<i...
alpha::foo is a dependent name, use alpha.template foo<int>(). Dependent names are assumed to not be types unless prefixed by typename not be templates unless directly prefixed by template
3,257,896
3,260,163
C++ for_each calling a vector of callback functions and passing each one an argument
I'm fairly green when it comes to c++0x, lambda, and such so I hope you guys can help me out with this little problem. I want to store a bunch of callbacks in a vector and then use for_each to call them when the time is right. I want the callback functions to be able to accept arguments. Here's my code right now. Th...
The problem with the long example is that my_func(_1,s) is evaluated right there and then. You need to use std::bind (or boost::bind) to invoke the function on each element in the range. The alternative code that you posted does indeed work, but the whole example fails to compile because of the code in do_callbacks: vo...
3,257,965
3,258,174
which size of struct member alignment in VC bring performance benefit?
does struct member alignment in VC bring performance benefit? if it is what is the best performance implication by using this and which size is best for current cpu architecture (x86_64, SSE2+, ..)
Perf takes a nose-dive on x86 and x64 cores when a member straddles a cache line boundary. The common compiler default is 8 byte packing which ensures you're okay on long long, double and 64-bit pointer members. SSE2 instructions require an alignment of 16, the code will bomb if it is off. You cannot get that out of ...
3,258,058
3,258,158
Aren't template class member functions compiled at instantiation?
I found a strange issue when porting my code from Visual Studio to gcc. The following code compiles fine in Visual Studio, but results in an error in gcc. namespace Baz { template <class T> class Foo { public: void Bar() { Baz::Print(); } }; void Print() { std::cout << "He...
gcc is right. It is because Baz is a namespace and namespaces are parsed top to bottom, so the declaration of Baz::Print is not visible from inside Foo (since it is beneath it). When the template is instantiated, only names visible from the template definition are considered, not counting Koenig lookup (which wouldn't ...
3,258,230
3,276,677
Passing a typename and string to parameterized test using google test
Is there a way of passing both a type and a string to a parametrized test using google's test. I would like to do: template <typename T> class RawTypesTest : public ::testing::TestWithParam<const char * type> { protected: virtual void SetUp() { message = type; } }; TEST_P(RawTypesTest, Foo) { ASSERT_STR...
Value parameterized tests won't work for passing type information; you can only do that with typed or type parameterized tests. In both cases you'll have to package your type and string information into special structures. Here is how it can be done with type-parameterized tests: template <typename T> class RawTypesTes...
3,258,248
3,258,466
Is it possible to construct an "infinite" string?
Is there any real sequence of characters that always compares greater than any other string? My first thought was that a string constructed like so: std::basic_string<T>(std::string::max_size(), std::numeric_limits<T>::max()) Would do the trick, provided that the fact that it would almost definitely fail to work isn't...
I assume that you compare strings using their character value. I.e. one character acts like a digit, a longer string is greater than shorter string, etc. s there any real sequence of characters that always compares greater than any other string? No, because: Let's assume there is a string s that is always greater ...
3,258,269
3,258,538
SomeClass* initialEl = new SomeClass[5];
Should SomeClass* initialEl = new SomeClass[5]; necessarily compile, assuming SomeClass does not have a non-publicly declared default constructor? Consider: /* * SomeClass.h * */ #ifndef SOMECLASS_H_ #define SOMECLASS_H_ class SomeClass { public: SomeClass(int){} ~SomeClass(){} }; #endif /* SOMECLASS_H_...
No, it won't compile without a default constructor. There is no compiler-generated default constructor in this case, because you have defined another constructor. "The compiler will try to generate one if needed and if the user hasn't declared other constructors." -- The C++ Programming Language, Stroustrup If you real...
3,258,312
3,258,622
SetWindowsHookEx for Mac OS X?
Windows hooks allows you to poke inside other processes and sometimes alter their behaviors. Is there such thing for Mac OS X? Thanks!
SetWindowsHookEx is more like the old InputManager hack, in the sense that you change the code of an app from inside a shared library / a plugin loaded to it. See SIMBL for a ready-made code injector to another process. For Objective-C classes, you then need to use method swizzling. I haven't tried replacing C function...
3,258,448
3,258,513
Show Delphi And C++ Source Code
How can I see the source code of an executable compiled by Delphi or C++? Please help me. After Edit: I have a program. When I start this program, it shows a dialog and asks for a password. This password is saved in source code. I want to take this password quickly and easily.
You can't. An enormous amount of information is thrown away when the compiler reduces human readable text source code down to machine executable code. Local variables don't need names in machine code, for example, they're just register bits in the instruction opcode. This is why debugging a compiled executable to st...
3,258,789
3,258,894
C++ vectors question
Does anyone know how to speed up boost::numeric::ublas::vector? I am using typedef ublas::vector<float, ublas::bounded_array<float, 3> > MYVECTOR3 and compare it's speed to D3DXVECTOR3 on plain operations. The test look the following way: #include <d3dx9.h> #pragma comment(lib, "d3dx9.lib") static const size_t kRuns =...
Boost uBLAS (and BLAS in general) provides support for vector and matrix algebra, where number of dimensions is determined in runtime. It is suitable for solving certain numerical problem (like simulation with FEM or similar method, optimization problems, approximation). For these problems it's relatively fast but cann...
3,258,831
3,258,859
Behavior of STL remove() function - only rearrange container elements?
I've read here on StackOveflow and other sources that the behavior of the remove function is simply re-ordering the original container so that the elements that are TO BE REMOVED are moved to the end of the container and ARE NOT deleted. They remain part of the container and the remove() function simply returns an ite...
What's left at the end of your container after a call to remove is not necessarily the elements that were removed. It's just junk. Most likely it's "whatever was in those positions before the call to remove", but you can't rely on that either. Much like an uninitialized variable, it could be anything. For example, the ...
3,258,861
3,258,937
Iterate forward and then reverse over STL container
I have an STL container and I need to perform an action on each element in the container. But if the action fails on any element, I want to reverse the action on any elements that have already been changed. For example, if I had an STL vector with pointers to a number bankAccount classes and wanted to increase each ...
Here's what I would do: Move the try/catch outside the loop Create a duplicate of the bankAccounts container Iterate over the duplicate container, calling increaseBalance on each item If the loop sucessfully completed, swap() the original and the duplicate container The code would look something like this: std::vecto...
3,258,869
3,275,445
Qt Creator problem. UI changes not showing when project is built
I'm making changes to a form in Creator but when I build the changes are not being "refreshed". I've gone so far as to remove every element from the form and get rid of every stylesheet but when I build the project I get the same result; as if I had never made a change at all. What gives? Am I missing something obvious...
I guess you're using QtCreator 2.0? I found the same strange issue. You have two options: Remove the ui_{the_name_of_design}.h from the project's build dir. Then run qmake again. make clean or Build → Rebuild All But the second option even doesn't help with me. By the way that's why is good to use a different build d...
3,259,137
3,259,150
Can I read a dynamical length variable using fread without pointers?
I am using the cstdio (stdio.h) to read and write data from binary files. I have to use this library due to legacy code and it must be cross-platform compatible with Windows and Linux. I have a FILE* basefile_ which I use to read in the variables configLabelLength and configLabel, where configLabelLength tells me how m...
Just do: unsigned int configLabelLength; // 4 bytes* fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_); std::vector<char> configLabel(configLabelLength); fread(&configLabel[0], 1, configLabel.size(), baseFile_); The elements in a vector are contiguous. * I assume you know that unsigned int i...
3,259,366
3,316,664
Cross Compiler Binary Execute Error
I just built a cross compiler using crosstools "mips-unknown-linux-gnu-gcc" and I compiled a hello world program. The compilation went fine using the command: "mips-unknown-linux-gnu-g++ hello.cpp -o hello" but when I run the command "./hello" I get the following error: babbage-dasnyder 50% mips-unknown-linux-gnu-g++ ...
Just as a note, crosstools did say it could run a trivial program: testhello: C compiler can in fact build a trivial program. When you cross-compile to a different architecture, you are generating instructions for the new architecture and thus you may not be able to run these instructions on your current architecture...
3,259,684
3,259,729
Cannot convert 'this' pointer to Class&
Can someone tell why i'm getting this error when compling this class? class C { public: void func(const C &obj) { //body } private: int x; }; void func2(const C &obj) { obj.func(obj); } int main() { /*no code here yet*/}
The C::func() method doesn't promise that it won't modify the object, it only promises that it won't modify its argument. Fix: void func(const C &obj) const { // don't change any this members or the compiler complains } Or make it a static function. Which sure sounds like it should be when it takes...
3,259,686
3,265,881
std::tr1::function and std::tr1::bind
I have a problem using a very complicated C function in a C++ class (rewriting the C function is not an option). C function: typedef void (*integrand) (unsigned ndim, const double* x, void* fdata, unsigned fdim, double* fval); // This one: int adapt_integrate(unsigned fdim, integrand f, void*...
If you are just trying to pass a member function into a c-style callback, you can do that with out using std::t1::bind or std::tr1::function. class myIntegrator { public: // getValue is no longer const. but integrandF2 wasn't changed double getValue( double x, double Q2 ) { m_x = x; m_Q2 = Q2; ...
3,259,728
3,273,591
Using Qt signals and slots with multiple inheritance
I have a class (MyClass) that inherits most of its functionality from a Qt built-in object (QGraphicsTextItem). QGraphicsTextItem inherits indirectly from QObject. MyClass also implements an interface, MyInterface. class MyClass : public QGraphicsTextItem, public MyInterface I need to be able to use connect and discon...
You found the answer yourself: the dynamic_cast works as you would expect. It is not undefined behavior. If the instance of MyInterface you got is not a QObject, the cast will return null and you can guard yourself against that (which won't happen, since you said all instances of the interface are also QObjects). Remem...
3,259,741
3,259,766
How do I use a priority queue in c++?
For example we have priority_queue<int> s; which contains some elements. What will be correct form of the following code: while (!s.empty()) { int t=s.pop();// this does not retrieve the value from the queue cout<<t<<endl; }
Refer to your documentation and you'll see pop has no return value. There are various reasons for this, but that's another topic. The proper form is: while (!s.empty()) { int t = s.top(); s.pop(); cout << t << endl; } Or: for (; !s.empty(); s.pop()) { cout << s.top(); << endl; }
3,259,848
3,259,885
c++: set<customClasS* how to overload operator<(const customClass&*...)?
Good Evening (depending on where u are right now). I am a little confused with the stl stuff for sorted sets... I want to store pointers of a custom class in my set and I want them to be sorted by my own criterion and not just the pointer size. Anyone has an idea how to do this? Since it is impossible to do it like op...
std::set's second template parameter is the method it uses for comparisons. So you can do something like this: struct dereference_compare { template <typename T> bool operator()(const T* pX, const T* pY) const { return *pX < *pY; } }; typedef std::set<T*, dereference_compare> set_type;
3,259,849
3,259,890
How to eliminate the '\n' at the end of a txt file
I'd like to eliminate the extra '\n' at the end of a txt file. Which function can be used to do this job in c / c++. Thanks advanced
One approach would be to iterate of the file line-by-line using getline, saving off that data for later. After each line is read, write the previous line (with \n). When no more data is available write the final line without the \n anymore. Alternately seek to the end to get the size, read the data in blocks of some ch...
3,259,934
3,260,037
Clearing Contents of a File in C++ knowing only the FILE *
Is it possible to clear the contents (ie. set EOF to the beginning/reset the file) in C++ knowing just the FILE*? I'm writing to a temp file with wb+ access and wish to sometimes clear it and truncate it without adding the calls to fclose and fopen. I dont think it's possible... but if not, why not? Thanks in advance!
It will depend on your platform. The POSIX standard provides ftruncate(), which requires a file descriptor, not a FILE pointer, but it also provides fileno() to get the file descriptor from the FILE pointer. The analogous facilities will be available in Windows environments - but under different names.
3,260,022
3,260,051
How to handle a float overflow?
If a float overflow occurs on a value, I want to set it to zero, like this... m_speed += val; if ( m_speed > numeric_limits<float>::max()) { // This might not even work, since some impls will wraparound after previous line m_speed = 0.f } but once val has been added to m_speed, the overflow has already occurred (and...
You could do: if (numeric_limits<float>::max() - val < m_speed) { m_speed = 0; } else { m_speed += val; } Another method might be: m_speed += val; if (m_speed == numeric_limits<float>::infinity()) m_speed = 0; But do keep in mind when an overflow actually occurs, the result is undefined behavior. So while...
3,260,072
3,260,308
Calling command prompt from Qt application without freezing?
In my Qt GUI application, I am calling the command prompt through: system("lots.exe & of.exe && commands.exe"); It opens up the command prompt (like I want it to), but freezes the Qt GUI application until I close the command prompt. Is there someway to prevent this? I saw that there is a QProcess class, but can't get...
QProcess is really the answer. If you want to use something like system() you'll have to either put the call in another thread or use popen or something simmilar for your platforms. QProcess does have the setReadChannel which you could use to display your own console window to show the output.
3,260,172
3,260,232
My Cross Compiler Always Compiles the Same File
I'm testing to make sure that my cross compiler is working. When I compile hello world it seems to compile fine but when I change hello.cpp to the same program that loops 1000 times the elf file generated is exactly the same size. No matter what changes I make the file is always the same size and as far as I can tell...
Without more details, it would be hard to help you much. But here are some ideas: As Bobby says, are you sure that you're passing the right files to it? Are you sure that the executable that you're running is the one being generated? Is the compilation actually succeeding? The executable you're running could be the on...
3,260,296
3,284,855
Error w/ C++ poco and HTTPSStreamFactory
I am trying to build a C++ app to access a XML resource. Using http the code works fine, from what I can tell from the docs, all I need to do to for the https to work is to make sure ssl is install (yes the dev edition is installed), and change the StreamFactory to HTTPSStreamFactory. Here is the code that works : Poco...
I ended up going about it a different way : Here is what I did. const Poco::URI uri(xmlParams.restURI); std::string path(argv[1]); const Poco::Net::Context::Ptr context = new Context(Context::CLIENT_USE, "", "", "", Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); Poco::Net::HTTPSCl...
3,260,517
3,260,596
Storing map's first element to a vector in the most generic form. Best solution
My goal is to store all the keys of a map (first item) to a vector and I'm doing the following. template < class vecDet> class storeInto { public: storeInto(vecDet& source) : VectorInfo(source) { } ~storeInto(); template <class pairdet> void operator()(pairdet& pairinfo) { VectorInfo.push_back(pairin...
Your code looks like it would work at first glance. However, there's a much simpler way to do this: I haven't evaluated your code, but there is certainly a much easier way to do what you want built into most STL implementations: vecContents.resize(mapContents.size()); std::transform(mapContents.begin(), mapContents.en...
3,260,601
3,260,709
How to use KDTree to make top-k query and range query on arbitrary dimensions
I have used KD-tree(libkdtree++) to store a multi-dimensional data set, and the requirements here is this data set can support top-k/range queries on different dimensions. For example, a KDTree<3, Point> tree: to find the top 100 points whose have highest Point[1](y axis) values. From the implementation of libkdtree++...
Looking at the code, it looks like you can't do that in a straightforward way, ridiculously enough. If I were you I'd be tempted to either hack the library or write my own kd-tree. I'd ask on their mailing list to be sure, but it looks like you might have to do something like this: kdtreetype::_Region_ r(point_with_m...
3,260,922
3,260,963
__typeof -identifier not found
For some reason I keep getting error C3861: '__typeof': identifier not found when I compile my program! I'm including the following libraries: <iostream> <stdlib> <stdio> Any ideas? thanks Edit: More example User.h class User{} main.cpp void f(User* p) { . . . __typeof(p) ... . . . . }
http://msdn.microsoft.com/en-us/library/x2xw8750%28VS.71%29.aspx __typeof only exists for /clr:oldSyntax. Are you trying to use Managed extensions to C++ or are you expecting __typeof to work like C++0x's decltype? If so, if you are using VS 2010 you can use decltype.
3,260,942
3,260,975
removing duplicates from a c++ list
I have been looking for an effective solution to remove duplicates from a C++ list. The list consists of pointers to a class object which has an attribute ID. I want to remove duplicates based on that ID. for my purpose, the unique method of the STL list will work in which we can pass a BinaryPredicate. i.e. void uniqu...
You could write a function like: bool foo (int first, int second) { return (first)==(second) ); } Also, you might need to declare the function as static if your using it in class.
3,260,947
3,264,137
How is this 3D rendering on the desktop done
I read a topic on OpenGL.org where a guy made this: http://coreytabaka.com/programming/cube-demo/ He said to release the source code but he never did, does anyone how I could get the same idea? Has to do with clearing the window with alpha but drawing on it as well.. just don't get how to get OpenGL setup like that. Fr...
Render the 3d scene to a pbuffer. Use a color key to blend the pbuffer to screen.
3,261,093
3,261,131
Function template in a namespace in a separate file compiles fine, but the linker cannot find it
This problem is in defining and declaring a function template in a namespace that is defined in an external file from where the function is instantiated. Here's the smallest reproducible example I could come up with. 4 files follow: The function template declaration in a named namespace: // bar.h #include <algorithm> ...
You are trying to hide the implementation of your templated function into the cpp file, which, unfortunately, is not possible for most compilers. Templated functions/classes are instantiated when used, so at the point where you are calling DoSomething, the compiler needs the definition of the function to be able to com...
3,261,128
3,261,261
Do templates support variable numbers of parameters
I'm trying to determine if the following scenario is appropriate for a template, and if so how it would be done. I have a base class, event_base. It is inherited by specific types of events. class event_base_c { //... members common to all events ... // serialize the class for transmision virtual std::stri...
C++ does not support variadic templates, but C++0x will, and some compilers already have support for this (including G++ with the --std=c++0x flag). Wikipedia has examples of how to use this feature.
3,261,178
3,261,189
What is an lvalue reference to function?
In §14.1.4, the new C++0x standard describes the non-types allowed as template parameters. 4) A non-type template-parameter shall have one of the following (optionally cv-qualified) types: integral or enumeration type, pointer to object or pointer to function, lvalue reference to object or lvalue reference to functio...
Your func_t is of type pointer to function; you can also declare a type that is a reference to a function: typedef int (&func_t)(int, int); Then your main() would look like so: int main() { Foo<add> adder(7,5); Foo<sub> subber(7,5); std::cout << adder.do_it() << std::endl; std::cout << subber.do_it() ...
3,261,227
3,318,224
How to serialize an object to send over network
I'm trying to serialize objects to send over network through a socket using only STL. I'm not finding a way to keep objects' structure to be deserialized in the other host. I tried converting to string, to char* and I've spent a long time searching for tutorials on the internet and until now I have found nothing. Is th...
I got it! I used strinstream to serialize objects and I sent it as a message using the stringstream's method str() and so string's c_str(). Look. class Object { public: int a; string b; void methodSample1 (); void methosSample2 (); friend ostream& operator<< (ostream& out, Object& object) { out << object.a << " " << ...
3,261,242
3,261,249
problem with casting float -> double in C when fread
I have a problem with casting from float to double when fread; fread(doublePointer,sizeofFloat,500,f); if i change double pointer to float pointer, it works just fine. However,i need it to be double pointer for laster on, and i thought when i write from small data type (float)to bigger data type(double)'s memory, it...
If you write float-formatted data into a double, you're only going to get garbage as a result. Sure, you won't overflow your buffer, but that's not the only problem - it's still going to be finding two floats where it expects a double. You need to read it as a float, then convert - casting (even implicitly) in this man...
3,261,400
3,262,617
C++0x passing arguments to variadic template functions
What does it mean to take a variable number of arguments by reference? Does it mean that each of the arguments are passed by reference? Consider for example the following functions which performs some processing on each its arguments: void f() // base case for recursion { } template <typename Head, typename ... Tail...
I think your intuition is correct, you can read all the details from the current draft ISO spec (it is not finalized yet) and you can test them out with GCC > 4.3
3,261,402
3,261,447
what is the equivalent to passing by address in c#
void Afunction(int* outvar) { if(outvar) *outvar = 1337; } note the qualities: it allows you to optionally pass a variable by reference, so that it can be set by the function. my closest guess would be (ref int? outvar) but that produces ref (int?) NOT (ref int)? which is what I need this functionality is...
The best you can get in C# is Action<int>, like this: void MyFunction(Action<int> valueReceiver) { if (valueReceiver != null) valueReceiver(1337); } Usage: MyFunction(null); MyFunction(v => someVariable = v);