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
7,561,828
7,561,847
Variable name from macro argument
I'd like to do something like this: class SomeClass { }; GENERATE_FUNTION(SomeClass) The GENERATE_FUNCTION macro I'd like to define a function whose name is to be determined by the macro argument. In this case, I'd like it to define a function func_SomeClass. How can that be done?
#define GENERATE_FUNCTION(Argument) void func_##Argument(){ ... } More information here: http://en.wikipedia.org/wiki/C_preprocessor#Token_concatenation
7,561,844
7,561,872
What can I do to fix that Visual Studio won't display per file properties?
I went to go turn on precompiled headers in a brand new project, so I went to go create the "/Create" setting for precompiled headers. But the property page is blank. What happened, and how can I fix this?
This looks like a COM registration issue. It's hard to tell what caused it but the best bet for fixing is to repair the Visual Studio install. That should fix the issue. Go to Control Panel and run "Add / Remove Programs" Double click on "Visual Studio 2010 ..." Click Next on the installer Choose Repair / Reinstal...
7,562,232
7,562,369
Random access to hash map values
What's the best way to design such a container, which can support randomized value access? but the container has to support other operations, such as insert key/value pairs and remove by key, with the best possible time performance. One way to do this is to combine hash map with array, but if hash map is used, what's t...
If you're talking about data structures, and not existing language support - then you just have to design a data structure to support that. You can do that, for example, by implementing a hash map which will hold, in addition, an array of pointers to its members. You can then translate random access operators to that a...
7,562,335
7,568,997
What is the correct way to programmatically quit an MFC application?
Using windows MFC C++. I have a third party app that calls a user-defined method in my CWinApp derived class. This method is called after InitInstance(). If there is an error in this method, such that an exception is thrown and caught in a try/catch block, I would like to exit the application from the catch block. ...
In InitInstance() Exiting the app while you are still in InitInstance(): Simply return FALSE from InitInstance(). In the main message loop It's another story though if you are already in the message loop: The standard way to close an app is to exit the message loop: PostQuitMessage(0), as its name implies, posts a WM_Q...
7,562,356
7,562,576
c++11 foreach syntax and custom iterator
I am writing an iterator for a container which is being used in place of a STL container. Currently the STL container is being used in many places with the c++11 foreach syntax eg: for(auto &x: C). We have needed to update the code to use a custom class that wraps the STL container: template< typename Type> class SomeS...
You have two choices: you provide member functions named begin and end that can be called like C.begin() and C.end(); otherwise, you provide free functions named begin and end that can be found using argument-dependent lookup, or in namespace std, and can be called like begin(C) and end(C).
7,562,409
7,562,536
Is there any advantage to the pimpl idiom with a templated class?
It is my understanding that the primary benefit of the pimpl idiom is to hide the data members in the implementation file instead of the header. However, templates need to be fully defined in the header in order for the compiler to instantiate them on demand. In this case, is there any advantage to using the pimpl idio...
While the pimpl idiom doesn't really hide anything when used in a templated class, it does allow you to easily write non-throwing swaps (although with C++11 move semantics this is less of a concern).
7,562,429
7,566,833
Adding a custom Authors category to Gtk::AboutDialog class
I was wondering if there was a way to set a custom Authors category in a Gtk::AboutDialog class via gtkmm. I know there are the following methods: set_artists() set_authors() set_documenters() set_translator_credits() But I wanted to add a custom category. Right now I have a program that accepts a bunch of plugins,...
Nice question! In GTK 3, this is fairly easy. You have to do some manipulation of the About dialog's internal children, which may change in future releases, so be warned! I've written a quick-n-dirty example in Vala that does what you want. That was faster for me because I almost never use Gtkmm. It shouldn't be too ha...
7,562,532
7,562,548
OpenGL: VBO functions are not defined
I'm trying to use OpenGL VBO's, but the functions associated with their use, glGenBuffersARB() for instance, are all undefined. Immediate mode functions are fine of course, it's only these. I'm using VS2010, with the SFML library. One of the include headers in that library includes both <GL/gl.h> and <GL/glu.h>, and ...
GLEW will define them, as will other GL extension libraries. Information can be found here: http://www.opengl.org/resources/features/OGLextensions/ Using an extension that includes new function call entry-points is harder in Win32 because you must first request the function pointer from the OpenGL ICD driver before yo...
7,562,534
7,562,811
What problems could warning C4407 cause?
I got some warnings by using pure virtual interfaces on some MFC CWnd derived objects through multiple inheritance. I believe it's caused by defining the methods which need to be implemented for the message map. warning C4407: cast between different pointer to member representations, compiler may generate incorrect cod...
An excellent description of the different representations of pointer-to-member values can be found at the article Member Function Pointers and the Fastest Possible C++ Delegates. Essentially, all the different inheritance types can require the use of different member function pointer representations. This is compiler-s...
7,562,535
7,570,283
RTOS: windows ce: can I perform all my calculations in kernel mode for a PID control loop?
In Windows CE, can I do all my calucation for a PID(Proportional-Integral-Derivative) control loop in "kernel mode" and avoid using "user mode"? I will transfering data over TCP=IP to another machine for the end result to keep the system in "kernel mode". My understanding is that switching from "kernel mode" to "user ...
I think you can do that, you should call SetKMode function to put your thread out or in of kernel mode. More details in these two blog posts from CE team: What is Kernel Mode? and Inside Windows CE API Calls.
7,562,609
7,562,682
What does `<cuchar>` provide, and where is it documented?
The new C++11 standard mentions a header <cuchar>, presumably in analogy to C99's <uchar.h>. Now, we know that C++11 brings new character types and literals that are specifically designed for UTF16 and UTF32, but I didn't think the language would actually contain functions to convert the (system-dependent) narrow mult...
These were described in a WG21 paper from 2005 but the description is not present in the final standard. They are documented in ISO/IEC 19769:2004 (Extensions for the programming language C to support new character data types) (draft), which the C++11 standard refers to. The text is too long to post here, but these are...
7,562,684
7,562,715
logical operations between chunks of memory?
I want to or two big chunks of memory... but it doesn't work Consider I have three char * bm, bm_old, and bm_res. #define to_uint64(buffer,n) {(uint64_t)buffer[n] << 56 | (uint64_t)buffer[n+1] << 48 | (uint64_t)buffer[n+2] << 40 | (uint64_t)buffer[n+3] << 32 | (uint64_t) buffer[n+4] << 24 | (uint64_t)buffer[n+5...
Enclose the definition of to_uint64 in parentheses () instead of braces {} and get rid of the semicolon at the end. Using #define creates a macro whose text is inserted verbatim wherever it's used, not an actual function, so you were attempting to |-together two blocks rather than those blocks' "return values."
7,563,074
7,563,087
Using a class/struct/union over multiple cpp files C++
I am trying to create a class in C++ and be able to access elements of that class in more than one C++ file. I have tried over 7 possible senarios to resolve the error but have been unsuccessful. I have looked into class forward declaration which doesen't seem to be the answer (I could be wrong). //resources.h class Ja...
The variable jam is defined in the H file, and included in multiple CPP classes, which is a problem. Variables shouldn't be declared in H files, in order to avoid precisely that. Leave the class definition in the H file, but define the variable in one of the CPP files (and if you need to access it globally - define it ...
7,563,197
7,563,221
std::vector, element pointer and input interator
I don't have my copy of Meyer's Effective C++ with me, so please forgive the question. template <class InputIterator> void insert ( iterator position, InputIterator first, InputIterator last ); For vector's insert, is a byte* to a raw memory block a valid InputIterator? typedef unsigned char byte; vector<byte> my...
Yes, a pointer is an input iterator.
7,563,218
7,563,277
Linking multiple times a single cross platform object file?
If I compile a cross-platform piece of code into an object file, will it be possible to use the linker to create separate platform-dependent executables (.exe,.bin) from that single binary file? EDIT: It seems the answerers don't really understand my question. I'm asking if you can use a cross-platform object and gener...
That pretty much depends entirely on the linker and other development tools that you have. Certainly cross compilation is possible in an advanced environment like gcc, where you can generate object code for different architectures. But packaging all those different-architecture objects into a single executable is not s...
7,563,287
7,563,305
C++ class whose member is a struct: Cannot understand compiler error
I want to create a class one of whose private: members is a struct point(see below). The public members ndim and numparticles are set at run-time by the user, which are used to create corresponding arrays inside the class . However I am getting a compiler error. I don't understand where I messed up. The compiler error ...
nbdsearch.h:31: error: array bound is not an integer constant before ‘]’ token double cood[ndim]; Array size needs to be a compile time constant and ndim clearly isn't. ndim is a variable. error: ‘point’ does not name a type point particlevec[numparticles]; On line 25, compiler doesn't know what point is. The str...
7,563,319
7,563,328
What is this error in the code?
while working in try-catch in came across this error. But I cant trace out the reason for this error though I surfed the net and SO. My code is... int main() { Queue q; int choice,data; while(1) { choice = getUserOption(); switch(choice) { case 1: cout<<"\nEnter an element:"; cin>>data; q.en...
You can't have a catch without a try. Put the line: try { before your while statement. If you want to get rid of the warnings about the string constants, you'll probably have to change the types to const char * or explicitly cast/copy them. Or you can use the -Wno-write-strings option to gcc.
7,563,332
7,563,342
C++ Saving/Loading a function as bytes. Getting the size of a function
Ok so I've used function pointers for some time. I was trying to figure out if this was possible. First. It IS possible to convert a function pointer into an array of bytes. It is also possible to reconstruct that function with the bytes in that array. I would like to save a function into an array of bytes, and lets sa...
What you're trying to do is not possible in C/C++. First of all, functions may not be contiguous in memory in the binary. So there's no definite "size". Secondly, you can't just load it into another program and execute it because it will violate memory protection (among other things, like address space). Lastly (if you...
7,563,367
7,563,391
including c++ libraries in ios programming
I'm developing an ios app that's very basic and uses objective almost all of the time. However my app needs to deal with big integer numbers (eg: 2^200) and add and multiply them. To achieve that I need to include a c++ library called bigint that allows these operations on huge integers. The problem I have is that when...
You can mix in C++ files, but use a .cpp suffix for them (and .hpp for their corresponding header files). If you want to mix C++ and Obj-C in the same file, you can do that, but give it a .mm suffix.
7,563,512
7,586,015
How to use QSortFilterProxyModel to filter a tree model that only display children nodes with their parents?
I have a working tree model derived from QAbstractItemModel and I wish to filter it using a QSortFilterProxyModel subclass to display only children nodes of certain criteria. For example I have the following tree: A - B -- C1 -- C1 -- C1 --- C2 - D - E I want to filter this tree with the condition that the node has na...
Okay, I've found a solution to my problem. Just use QTreeView::setRootIndex() with index B as the input argument. Index B becomes the root index of the QTreeView, which is hidden and only its children are shown in full. I felt really dumb after finding this solution. Guess I was too focused on using the proxy model to ...
7,563,741
7,563,778
c++ generic pointer? void pointer?
I am writing a program that can take in either 3 ints, or 3 floats in the constructor(I suppose I will need 2 constructors for this). I want to declare an array and store the values in the array "numbers". If I don't know which constructor will be called I am not sure how to declare "numbers"(as an int array or as a...
Looks like you want a templated class. template <class T> class Foo { public: Foo(T a, T b, T c) { numbers[0] = a; numbers[1] = b; numbers[2] = c; } private: T numbers[3]; };
7,563,818
7,564,018
Why does this make an infinite loop
#include <iostream> #include <math.h> using namespace std; int main() { double radius = 0.00; double height = 0.00; double width = 0.00; double side = 0.00; double Area = 0.00; const double PI = atan(1.0)*4; string input = "none"; while (input != "0") { cout << "Shape Menu: \n ...
You are using cin.clear() and cin.ignore(1000,'\n') to skip over the invalid input in the rectangle case, which is good, but you aren't doing that in the other cases.
7,564,033
7,564,042
Difference between char* and char[]
I know this is a very basic question. I am confused as to why and how are the following different. char str[] = "Test"; char *str = "Test";
char str[] = "Test"; Is an array of chars, initialized with the contents from "Test", while char *str = "Test"; is a pointer to the literal (const) string "Test". The main difference between them is that the first is an array and the other one is a pointer. The array owns its contents, which happen to be a copy of "T...
7,564,064
7,564,102
error: 'int main(int, char**)' previously defined here in C++
I'm implementing gtest now, and it gives me an error : main previously defined here. Here's utest.cpp // Bring in my package's API, which is what I'm testing #include "../src/test.cpp" // Bring in gtest #include <gtest/gtest.h> // Declare a test TEST(TestSuite, testCase1) { EXPECT_EQ(5,getX(5)); } // Run all the...
The error message states what the problem is, you have two main() functions. I believe you want to remove the duplicate main() from test.cpp.
7,564,150
7,564,218
General knowledge question regarding classes and class instances in C++
I'll start with my problem: My problem is that I'm getting a segmentation fault when I try to access a public function within an instance within a class. Suppose I have a class A that has a bunch of class instances in it like so: class A { ... public: class B *B; class C *C; }; Let's consi...
In general your code will segfault if you dereference a pointer to an unitialized variable. From your description, this sounds like what is happening, although it's hard to tell given the lack of an example that fails. another function in A instantiates the B class. Would my C class be able to use that B class? Yes...
7,564,186
7,564,288
What is the easiest way to turn an array of RGB values in C++ into an image file?
I've been looking all over the net for a good, quick solution to this, and haven't found anything that has satisfied me yet. It seems like it should be trivial--just one or two calls to a function in some library and that's it--but that doesn't seem to be the case. libjpeg and libtiff lack good documentation and the so...
If you want "simple" over anything else, then have a look at stb_image_write.h. This is a single header file, which includes support for writing BMP, PNG and TGA files. Just a single call for each format: int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); int stbi...
7,564,342
7,564,420
What are the arguments against using size_t?
I have a API like this, class IoType { ...... StatusType writeBytes(......, size_t& bytesWritten); StatusType writeObjects(......, size_t& objsWritten); }; A senior member of the team who I respect seems to have a problem with the type size_t and suggest that I use C99 types. I know it sounds stupid but I alwa...
Use exact-size types like uint32_t whenever you're dealing with serialization of any sort (binary files, networking, etc.). Use size_t whenever you're dealing with the size of an object in memory—that's what it's intended for. All of the functions that deal with object sizes, like malloc, strlen, and the sizeof opera...
7,564,491
7,564,611
C++ equivalent of .ToString()
There must be an easy way to do this... // C# code for (int i = 0; i < 20; i++) doSomething(i.ToString() + "_file.bmp"); I'm trying to do this in C++, but it turns out that the simplest things are the hardest to do in that language. Mostly because there's a catch: I'm restricted to a library that only ...
I see several bugs in your code. 1) You declare "path" to be an array of 12 character pointers, but no memory allocated for the any of the array items. The sprintf statement is guaranteed to copy into garbage memeory. I'm surprised this doesn't crash your program right away. 2) And even if there was memory allocated f...
7,564,570
7,564,684
how to apply parallelism-programming in graph problems?
Problem Description: there is n tasks, and in these tasks, one might be dependent on the others, which means if A is dependent on B, then B must be finished before A gets finished. 1.find a way to finish these tasks as quickly as possible? 2.if take parallelism into account, how to design the program to finish these ta...
Topological sort algorithms may give you various different result orders, so you cannot just take the first few elements and assume them to be the independent ones. Instead of topological sorting I'd suggest to sort your tasks by the number of incoming dependency edges. So, for example if your graph has A --> B, A --> ...
7,564,595
7,564,617
Assigning negative value to char
Why does the following code print "?" ? Also how can -1 be assigned to an unsigned char? char test; unsigned char testu; //isn't it supposed to hold values in range 0 - 255? test = -1; testu = -1; cout<<"TEST CHAR = "<<test<<endl; cout<<"TESTU CHAR = "<<testu<<endl;
unsigned simply affects how the internal representation of the number (chars are numbers, remember) is interpreted. So -1 is 1111 1111 in two's complement notation, which when put into an unsigned char changes the meaning (for the same bit representation) to 255. The question mark is probably the result of your font/co...
7,564,647
7,564,731
std::enable_if specialisation failing
I've been messing around with enable_if, and I seem to have stumbled upon some inconsistent behaviour. This is in VS2010. I've reduced it to the following sample. #include <type_traits> using namespace std; // enable_if in initial template definition template <class T, class Enable = enable_if<true>> struct foo {}; ...
Your problem has very little to do with enable_if // you declare a structure named baz which takes 2 template parameters, with void // as the default value of the second one. template <class T, class Enable = void> struct baz; // Partial specialization for a baz with T and an std::enable_if<true> template <class T> str...
7,564,696
7,564,722
C++ strange behaviour
Please check this code.. class ex { int i; public: ex(int ii = 0):i(ii){} ~ex(){cout<<"dest"<<endl;} void show() { cout<<"show fun called"<<endl; } }; int main(int argc , char *argv[]) { ex *ob = NULL; ob->show(); return 0; } what happens when we call show me...
ex *ob = NULL; ob->show(); You're dereferencing a null pointer which causes undefined behaviour. This is bad. If it's not clear where the dereference is then understand that the -> operator translates to (*ob).show().
7,564,706
7,651,190
c++ visual studio 2010 exe in resource get Rebased?
Has anyone noticed that if you import an exe as resource it gets rebased and also seems that its PE header gets rebuilt? There are times that this is irritating. Does anybody knows how to disable the rebasing!? steps to reproduce in c++: 1) compile a hello world and manually set its base address (in properties) to lets...
How are you including the EXE as a resource into the second project? Using these defines: #define BINFILE 222 #define IDR_MYFILE 101 If I reference the executable in my .rc file as pointing to the original file, e.g.: IDR_MYFILE BINFILE "S:\\mysource\\t1\\Release\\t1.exe" Then, upon extraction, my embedded EXE resour...
7,564,942
7,565,013
c++: Getting a segfault when initialising a queue of pointers
I am trying to implement the BFS algorithm described in CLRS. And have the following: #include <iostream> #include <list> #include <queue> #include <string> #include <sstream> using namespace std; struct Node{ char colour; int numNbr; Node* parent; int distance; int* neighbours; int* costs; ...
list<Node*> bfs(... while you return: return l; also, no need for reference here: Node** &nodes And segfault didn't occur where you pointed. I/O buffers were not fulshed because of it and it loooks like this cout << "initialised a queue" << endl; list<Node*> l; cout << "initialised a list" << endl; wasn't executed
7,564,946
7,564,995
xml parsing is faster in C/C++ or Java?
I need to parse XML either in C/C++ or Java. Which one is fast? I think SAX parser will be ok with java Pl. help
Generally C++ is compiled to native code while java is compiled to byte code and then is interpreted at runtime. Therefore C++ code should theoretically run fater. But due to automatic memory management and other good features java development is much easier and faster. The big question is do you really ned some extra...
7,565,007
7,565,432
how to use VBO for morphing?
I want to have a mesh that can be animated. I'm loading mesh from a file, including key frames. I want to put all the frames into VBO and compose two of them on the GPU in a vertex shader. So i want to pass to frames to GPU and some uniform that will allow to create one result frame from these two Is it possible? If so...
You would just have more vertex attributes. Normally, you might have: in vec3 position; in vec3 normal; in vec4 color; in vec2 texCoord; With morph targets, you would need: in vec3 position0; in vec3 position1; in vec3 normal0; in vec3 normal1; in vec4 color; in vec2 texCoord; The actual model-space position would be...
7,565,034
7,565,111
Can multiple threads write into a file simultaneously, if all the threads are writing to different locations?
I am writing the code in c++. Can I run into any kind of race conditions or seg-faults?
There's no problem doing that from the point of view of the underlying system (for all systems I know). However, typically you would need to have completely separate file descriptors/handles. This is because the file descriptor maintains state, e.g. the current file position. You also need to check the thread-safety of...
7,565,083
7,566,172
Virtual function calling mechanism
class base { public: virtual void fn(){} }; class der: public base { public: void fn(){} }; der d; base *b = &d; b->fn(); When the compiler encounters the statement b->fn(), the following information is available to the compiler: b is a pointer to the class base, base class is having a virtual function as wel...
When reasoning about this, it helps me to maintain a clear image of the memory layout of the classes, and in particular to the fact that the der object contains a base subobject that has exactly the same memory layout as any other base object. In particular your base object layout will simply contain a pointer to the v...
7,565,089
7,565,638
How to Disable Auto-link for TBB
When I build my VS project as Debug, it always auto-linked with tbb_debug.lib (which in turn linked with tbb_debug.dll). Is there a way to override this and make tbb.lib linked even for a Debug build?
First, are you sure it is 'auto-linked'? If so, this is done using #pragma comment( lib, tbb_debug.lib ). Find where this code is, modify it if it's yours, or else disbale it somehow (either by do not including the file where that code is, or by #defining something that disables this piece code; any sane library writer...
7,565,404
7,574,749
Load a cubemap in a DDS file with DevIL
I only get the first face in a cubemap. How do I access/load the other ones? With DevIL 1.7.8 on Ubuntu Natty: I use ilLoad or ilLoadImage to load a dds-file with 6 textures, but only the first face gets loaded. ilGetInteger() give the results: IL_IMAGE_DEPTH: 1 IL_IMAGE_BYTES_PER_PIXEL:4 IL_NUM_LAYERS: 0 IL_NUM_IMAG...
DevIL does not have provisions for DDS Cubemaps. Neither do a surprising number of image loaders.
7,565,424
7,565,690
Insert Image to a Document
I am new to VC++, I want to know if it is possible to insert an image created by my kinect camera to a RTF doc or MSWord doc using VC++ in a Win32Console Application? Any pointers on how can I achieve my goal? Thanks!
Yes, it is possible. I assume that you already have a way to get the image from the camera and save it to a file. RTF (specification) is an utter pig, but the spec will tell you how to add an image. Parsing an existing file to figure out where to add the image though, or creating a new file with the image already prese...
7,565,691
7,565,779
Error in CreateProcessW: cannot convert parameter 9 from 'STARTUPINFO' to 'LPSTARTUPINFO &'
I understand that startup_info is a pointer to a STARTUPINFO structure I have a function which I pass startup_info by reference into it. So we can say that I am passing a pointer by reference void cp(....., LPSTARTUPINFO & startup_info) { CreateProcessW(....., startup_info); } Let us assume that I call function cp i...
You've got two startup_info's. In caller(), it's a STARTUPINFO (not a pointer). In cp(), it's a STARTUPINFO*& (reference to a pointer). Why? It's most likely unintentional. I'd expect: void cp(....., STARTUPINFO* pStartup_info) { CreateProcessW(....., pStartup_info); } void caller() { STARTUPINFO startup_info; ...
7,565,941
7,566,317
cout does no print in QtCreator
I saw this question already on this forum but I do not know why the proposed answer does not work in my case. So I try to ask for other slution. I just got my Qt creator running under Linux. I do not understand why my: cout << "This does not appear"; Does not print in console while qdebug does qDebug() << "This appear...
Try with: cout << "asdf" << endl; Possibly Qt sets up iostream in order to flush only at new line.
7,566,034
7,566,058
Header guard / translation unit problem
I was under the impression that header guards solve the problem of redefinition. I'm getting linker errors that say there are redefinitions in the .obj files. This is the header I'm including, the problems are with the redefinition of all the global declarations. #ifndef DIRECT3D_H #define DIRECT3D_H // global declara...
Header guards solve the problem of including the same header twice or hidden recursion of includes, not double definition. If you include the same header in different translation units, header guards won't help. The solution is to never declare variables in header files. If you need to share variables, use the extern k...
7,566,136
7,566,242
c++ macro concatation not worked under gcc
#include <iostream> void LOG_TRACE() { std::cout << "reach here"; } #define LOG_LL_TRACE LOG_TRACE #define LL_TRACE 0 #define __LOG(level) LOG_##level() #define LOG(level) __LOG(##level) int main() { LOG(LL_TRACE); return 0; } The code is worked under Visual Studio, but report: test.cpp:13:1: error: p...
Shouldn't it be : #define LOG(level) __LOG(level) That works: #include <iostream> void LOG_TRACE() { std::cout << "reach here"; } #define LOG_LL_TRACE LOG_TRACE #define __LOG( level ) LOG_##level() #define LOG(level) __LOG(level) int main() { LOG( LL_TRAC...
7,566,689
7,583,661
How to get CKA_ID from public/private Key pair of USB Token?
I have a USB token contain certificate, public/private key pair, how can i get #define CKA_ID Key identifier for public/private key pair (default empty). From PKCS 11 document using C++?
First find the certificate with CKO_CERTIFICATE. (C_FindObjectsInit, C_FindObjects, C_FindObjectsFinal) 2.Get the CKA_ID using C_GetAttributeValue
7,566,700
7,566,736
Replace the C socket API in C++ on z/OS
I am including sys/socket.h, I still get compile time errors telling me that AF_INET is not defined. but still i am facing the issues getting the C sockets API to work properly in C++. please help me...
check out the z/OS UNIX System Services sockets section in the z/OS XL C/C++ Programming Guide. Make sure you're including the necessary header files and using the appropriate #defines.
7,566,920
7,566,974
Windows Phone 7 SDK C or C++
Is there any way to use C or C++ on Windows Phone 7? Also i need access to OpenGL from C/C++ and some kind of adapter to C from, for example, C#.
Short answer: you cannot. You have to use C# and XNA. Long answer: There is no OpenGL API on WP7. You have to use XNA for 3D graphics. You cannot use C++, only managed (.Net) languages. I'm not an expert but I believe officially supported languages are C#, VB.net and F# at the moment. However, you may be able to use o...
7,566,949
7,567,022
QSql module and multithreaded application
I'm troubled by how the Sql module works with multithreaded application in Qt. http://doc.qt.io/qt-5/threads-modules.html#threads-and-the-sql-module clearly states that "A connection can only be used from within the thread that created it". However this piece of code I wrote works : #include <QCoreAppli...
The above code is fine because QSqlQuery creates its own QSqlDatabase. It would be a problem if it referenced _db as created by db(). The down side is that it doesn't actually do anything. QSqlDatabase is not a QObject but it has-a driver which is a QObject and therefore has thread affinity. If creating loads of QSqlDa...
7,567,034
7,567,859
Boost message_queue: just the constructor lets me configure it, no other member functions available
This is a classic Boost message_queue example: #include <boost/interprocess/ipc/message_queue.hpp> using namespace boost::interprocess; struct Data { ... }; int main() { Data data1; message_queue::remove("message_queue"); message_queue mq(create_only, "message_queue", 100, sizeof(Data)); mq.send(&da...
How about this : class QueueManager { boost::scoped_ptr<message_queue> mq; // ctor QueueManager(string msgqname) { mq.reset(new message_queue(create_only, msgqname, 100, sizeof(Data)); } }; Just to give you an idea that at least some parameters can be passed to class constructor. Since message queue ...
7,567,092
7,567,580
How to learn the link between C++ code and the generated assembly code?
My question is specifically for Windows C++ compilers and Visual Studio, but I got offered to interview for a job in finance where they wanted somebody very technical to write real-time multi-threaded code who could analyse at assembly level the code generated by a C++ compiler. What are the methods one can apply to le...
The first thing to do would be to learn the assembler and machine code. There is some very good documentation of the machine code available at the Intel site (although it may be more detailed than you need). There are two common assembler formats in widespread use: the one used by Microsoft is based on the original Int...
7,567,161
7,567,194
Using extern variables in visual studio 2010
I tried defining int GlobalVariable; in FileA.cpp and inside FileB.cpp, I tried to use GlobalVariable by declaring extern int GlobalVariable; but when I tried using GlobalVariable, I get 'GlobalVar' : undeclared identifier or some unresolved linking error, how do I go about making it work?
(Without having your code) Use this pattern: FileA.h extern int GlobalVariable; FileA.cpp int GlobalVariable = 1000;
7,567,226
7,569,265
how to merge two or more one dimensional boost::multi_array s?
I want to learn how to add an one dimensional multi_array to end of another one dimensional multi_array. How would i do that?
Boost multi-array has (not very well documented) iterators like any other container, so you can use them as normal. #include <boost/multi_array.hpp> #include <iostream> int main (int ac, char **av) { typedef boost::multi_array<int, 1> array_type; array_type::extent_gen extents; //create some arrays array_type...
7,567,281
7,567,343
STL set and map for the same user defined type
I have a class for which I have defined comparison operator. Following is the code I wrote #include <set> #include <map> #include <list> template <typename _TyV> class Element { public: Element(_TyV in) : m_Label(in){} ~Element() {} bool operator < ( const Element & right) const { ...
Your map, std::map<ElementType*, std::list<ElementType*> > uses std::less on the key type as its comparator, as normal. std::less for pointer types is defined to produce a consistent ordering, but the ordering is based on the address only, not on anything that it might point to. So, your set sorts its contents accordin...
7,567,556
7,567,620
Keep the class state in C++ after Returning to C#
I have a C++ as the backend and C# as the front end, I use pinvoke interop mechanism to communicate between the native and managed code. The issue now is that there are really two parts of computation done by the C++ backend, the initialization part and the compute-on-the-fly part. The initialization needs to be done ...
You could write a wrapper around your C++ class(es) in C++/CLI thus providing true CLR types. You can than manage their lifecycle in C# seamlessly. There is quite some information on the web for it: here or here (just google "C++/CLI wrapper"). And, naturally, on stackoverflow: here. Unless there is some nifty tool, ...
7,567,629
7,567,637
inclusion of header files
i have a file named functions.h....now i know that it is not wise to define functions in the header files but that is least of my concern as compared to the problem which cropped up... i defined a function in a functions.h named void sayhi() { cout<<"hi"; } now i made a lines.h file whose functions were defined in...
Well, the solution is to declare the function in functions.h and then define it in functions.cpp, the way nature intended.
7,567,872
7,569,013
How to create a program to list all the USB devices in a Mac?
I have a limited exposure to the Mac OS X operating system and now I have started using Xcode and am studying about I/O kit. I need to create a program in Xcode under command line tool in order to list all USB devices connected in a Mac system. Those who have previous experience under this, please help me. If anyone co...
You can adapt USBPrivateDataSample to your needs, the sample sets up a notifier, lists the currently attached devices, then waits for device attach/detach. If you do, you will want to remove the usbVendor and usbProduct matching dictionaries, so all USB devices are matched. Alternately, you can use IOServiceGetMatching...
7,567,883
7,569,028
Thread-safe initialisation of local statics: MSVC
Possible Duplicate: Is static init thread-safe with VC2010? I know that gcc and llvm-clang emit code to initialise local static variables in a threadsafe manner (which allows one to escape the static order initialisation fiasco by wrapping global statics in functions). This msdn blog post, however, is the best docum...
The C++0x Standard says: §6.7 Declaration statement [stmt.dcl] 4/ The zero-initialization (8.5) of all block-scope variables with static storage duration (3.7.1) or thread storage duration (3.7.2) is performed before any other initialization takes place. Constant initialization (3.6.2) of a block-scope entity with sta...
7,568,224
7,568,506
how to read constants from .h file in C#
I want to read the constants in C#, these constants are defined in a .h file for C++. Can anyone tell me how to perform this in C# ? The C++ .h file looks like: #define MYSTRING1 "6.9.24 (32 bit)" #define MYSTRING2 "6.8.24 (32 bit)" I want to read this in C# ?
Here is a really simple answer that you can use on each line of your .h file to extract the string value. string GetConstVal(string line) { string[] lineParts = string.Split(line, ' '); if (lineParts[0] == "#define") { return lineParts[2]; } return null; } So any time it returns null, you don't have a co...
7,568,263
7,568,387
Proper way to implement move semantics for class with std::vector of std::vector member
I have a class that has a member which is a vector of vectors. I would like to write a constructor for this class that takes an r-value reference to a single vector as an argument, and moves it into the member vector as a single element vector of the vector argument. So far I have: class AClass { std::vector<std::v...
It should be shorter to write: member[0] = std::move(vec); in order to invoke vector<T,Allocator>& operator=(vector<T,Allocator>&& x); As far as I know, explicit moving is necessary, because vec is not a rvalue (it is a named variable and can be used on the left side of operator=).
7,568,424
7,568,468
What winapi C function call can I use to convert unicode to ascii and vice versa?
It has to work with a C program so it has to be a winapi c call
That would be WideCharToMultiByte and MultiByteToWideChar.
7,568,559
7,568,705
Displaying image in MFC method that is not ONPaint
I am trying to display an image in a dialog dynamically, it works no problem if I put the code in the on paint method and use the dc from there, I can't do this though I need to display after the window is shown, the code I am using is as follows, I am getting the dc of the client window creating the bitmap from a reso...
I think there's more in the BeginPaint-function than just giving you the CDC. And BeginPaint can only be called from the OnPaint-method. To solve your problem, use the Invalidate-functions to force a repaint from your "SetupInstructions" method. Then do the drawing inside the OnPaint function.
7,568,607
7,568,982
Boost PropertyTree: check if child exists
I'm trying to write an XML parser, parsing the XML file to a boost::property_tree and came upon this problem. How can I check (quickly) if a child of a certain property exists? Obviously I could iterate over all children using BOOST_FOREACH - however, isn't there a better solution to this?
optional< const ptree& > child = node.get_child_optional( "possibly_missing_node" ); if( !child ) { // child node is missing }
7,568,611
7,568,637
initialisation of const member of base class into derive class
public: const int x; base():x(5){} }; class der : public base { public: der():x(10){} }; der d; My aim is when instance of base class is created it will initialise x as 5 and when instance of der class is created it will initialise x as 10. But compiler is giving error. As x is inherited from class base...
You can't initialize a base class member in the initializer list for a constructor in the derived class. The initializer list can contain bases, and members in this class, but not members in bases. Admittedly, the standardese for this isn't entirely clear. 12.6.2/2 of C++03: Unless the mem-initializer-id names a nonst...
7,568,697
7,568,805
Missing dlls on 64 bit Win
I have a .net application that uses some vc++ compiled Win32 dlls. It works great on a 32 bit Win, but on 64 bit there is a problem: "Unable to load DLL 'xyz': The specified module could not be found. (Exception from HRESULT: 0x8007007E)" Using dependency walker I found it misses the following dlls: MSVCP100.DLL, MSVCR...
The whole process should be 32 or 64 bit. If you cannot compile all dependency libraries in 64 bit, you need to run .NET project in 32 bit. To do this, create x86 configuration (default is Any CPU) and build .NET project in this configuration. You also need to install VC++ 2010 redistributable package on destination co...
7,568,711
7,569,025
Editable Console Output
Here is a portion of some code I am trying to write: //Choice Based Menu #include <iostream.h> #include <conio.h> int main() { char choice; cout<<"Menu"<<endl<<endl; cout<<"A. Option A"<<endl; cout<<"B. Option B"<<endl; cout<<"C. Option C"<<endl; cout<<"Q. Quit"<<endl; cout<<endl<<"Choice:\t...
This this: #include <iostream.h> #include <conio.h> int main() { char choice; cout<<"Menu"<<endl<<endl; cout<<"A. Option A"<<endl; cout<<"B. Option B"<<endl; cout<<"C. Option C"<<endl; cout<<"Q. Quit"<<endl; do { choice=getch(); cout << "\r" << "Choice:\t"; // Moved into ...
7,568,810
7,827,681
Xcode 4 external build project and debugging
I've got a makefile based project set up that builds my code on multiple platforms. On my Mac I want to use Xcode for debugging though. I've set up an Xcode as an External Build Project I can run the application from within Xcode. The output is shown in Xcode and if the app crashes it drops in to the debugger, but when...
I was able to fix the issue of not stopping at breakpoints by setting a custom working directory for the executable. Before this change I was able to build successfully using the external scons system from Xcode 4. My code would run when called from XCode but breakpoints would be ignored. Then in XCode, Go to Product ...
7,568,985
7,569,009
Does FreeBSD support memory mapped files?
I am using a FreeBSD OS, I want to write into a file which is on the disk, but, it will take a lot of time, so, I was suggested to use Memory mapped file. But, I am in a dilemma whether FreeBSD supports it or no???.. Please, somebody can guide me??.. I am programming in C++.
Yes, FreeBSD has memory mapped files. No, the STL does not include any special support for them. Consider using Boost.
7,569,226
7,569,272
Defining an output file stream within a class
How can I define an output file stream within a class, so that I don't have to keep passing it around to functions. Basically what I want to do is this: class A { private: ofstream otp ; }; Then in my constructor, I simply have otp.open("myfile"); and in other functions I have otp.open("myfile", ios::app); , but ...
You'll need to use the fully qualified name, std::ofstream.
7,569,566
7,569,646
extern pointer problem in c++
I have a header file that has a number of declarations like this: extern ID3D10Device* device; I can't make these static because of a problem with multiple translation units, and I can't have them as normal pointers for a similar reason. However when I try to build the program I get unresolved external symbol linker e...
You need the pointers to be defined in some translation unit. The linker is complaining because it seems you haven't done that anywhere. You should declare them at file scope as ID3D10Device* device = NULL; in the source file where you call the DirectX function that initializes them. Just make sure the declaration is ...
7,569,753
7,569,942
formatting a string which contains quotation marks
I am having problem formatting a string which contains quotationmarks. For example, I got this std::string: server/register?json={"id"="monkey"} This string needs to have the four quotation marks replaced by \", because it will be used as a c_str() for another function. How does one do this the best way on this strin...
it is perfectly legal to have the '"' char in a C-string. So the short answer is that you need to do nothing. Escaping the quotes is only required when typing in the source code std::string str("server/register?json={\"id\"=\"monkey\"}") my_c_function(str.c_str());// Nothing to do here However, in general if you want ...
7,569,851
7,570,243
Why isn't my C++ assembly signed?
I have a C++ project, set to /clr, which is referenced by C# projects in the same solution. Unfortunately, it seems the C++ doesn't get properly signed, leading to the error message "assembly doesn't have a strong name." (sn.exe agrees with that error.) However, there is an snk file in the project settings (Linker/Adva...
Ok, I found the solution: Apparently, MS blew the SP1 release for VS2010 and you have to go and mess around in the MSBUild installation folder. Here is an article giving the dirty details. (And why this would work in one project, but not in the other I have no idea. And, frankly, I've lost enough hours banging my head...
7,570,111
7,570,155
How to use System::Net::Mail in console application
How i can use this >> System::Net::Mail; namespace in c++ console application? Maybe im asking fool question but im new in cpp please help
see msdn static void CreateTestMessage2( String^ server ) { String^ to = L"jane@contoso.com"; String^ from = L"ben@contoso.com"; MailMessage^ message = gcnew MailMessage( from,to ); message->Subject = L"Using the new SMTP client."; message->Body = L"Using this new feature, you can send an e-mail message from ...
7,570,152
7,570,195
Object returned from function and copy constructor
There is such code: #include <iostream> class A { public: int a; A() : a(0) { std::cout << "Default constructor" << " " << this << std::endl; } A(int a_) : a(a_) { std::cout << "Constructor with param " << a_ << " " << this << std::endl; } A(const A& b) { a = b.a; ...
Why copy constructor is not called there? RVO How can be copy constructor forced to invoke in this case? Pass an option to the compiler. For gcc, it is --no-elide-constructors option to disable the RVO
7,570,165
7,570,594
How to declare structures of data that should only be used in a certain context, C++
I'm having a rather general design problem and would like to solve it nicely. I'm writing remote control drivers in an embedded C++ project. There will be two types of remote control: joystick or radio. As I'd like the actual remote controller used to be transparent to an user-programmer, I'm also providing a base clas...
It looks that RCInput is going to be just data, so you can lay it out like that: RCInput.h file class RCInput { public: RCInput(double x, double y, double z); double x() const; double y() const; double z() const; private: double m_x; double m_y; double m_z; }; RCInput.cpp file: RCInput::RC...
7,570,484
7,570,551
Benchmark C++ vs Java, Unrealistic results
I did a simple test, I know C++ is faster but the results of my test is unrealistic. C++ code is: #include <stdio.h> #include <windows.h> unsigned long long s(unsigned long long n) { unsigned long long s = 0; for (unsigned long long i = 0; i < n; i++) s += i; return s; } int main() { LARGE_I...
Show the compiler options you used. And your REAL code (#include <stdio> isn't your real code). Your C++ compiler is much smarter than your Java compiler (this is true on average and in your case, but not every C++ compiler is smarter than every Java compiler), and it precomputed the result. The only thing you're tim...
7,570,486
7,570,618
How can you factor out branching from tight loop?
My question is: How can I add features to my processing loop without the overhead of checking the true/falseness of the user settings to navigate the branches? The settings are the same for all iterations on the loop. Do modern processors with branch prediction make this unnecessary? My programs over follow this patter...
Use templates for the main loop. template <bool A, bool B> void loop() { while (1) { if (A) // will get compiled out if A == false { doStuff(data[i]); .... } if (B) { doMoreStuff(data[i]); ..... } .... //etc } } When you change settings...
7,570,538
7,570,714
why try...catch requires EXACT type thrown
I can do this, no problem: long lngval = 3L; int i = lngval; but if I try this: try { throw 3L; } catch(int i) { cout << "caught " << i << endl; } I get an unhandled exception. This seems inconsistent. what is the reason for no type conversion in this case?
In the first case, the compiler can tell exactly what you want to do: convert a long to an int. In the second case, the compiler has to assume that you might have a construct like this: try { try { throw 3L; } catch (int i) { /* P */ } } catch (long l) { /* Q */ } The idea is that the compiler can never kno...
7,570,605
7,570,637
Can C++ code be called from a Java applet?
I'm curious if I can do this. Can C++ code compiled and loaded on the local host be called from a Java applet running in a browser?
Yes, it can be done if your applet is signed and the user agrees to grant the Applet full privileges.
7,570,647
7,570,712
C++ Outputting text on a window
Simple question, is drawing text using functions like TextOut or DrawText better then creating a static control, performance wise? And which has better performance TextOut or DrawText?
Second question first: DrawText calls TextOut, so if you don't need the formatting capabilities of DrawText, you can go straight to TextOut. If raw performance is all you care about, then drawing directly will be faster. However, raw performance should not be your sole concern. It is also more work and does not support...
7,571,238
7,571,271
"dynamic constructor" in c++
i am new to classes in C++ and i need to create a class "Plot" which has a method that reads in data from a file and creates a 3d grid. i understand that you can make "default" constructors with default values or you can create a special constructor with predefined values. in my "private" section, i have: int nx; // nu...
Use std::vector grid; as your member. Then you can use grid.resize(nx*ny*nz) to force the size you want or use grid.push_back(value); for each value you want to add to the array.
7,571,278
7,571,340
How do I define string constants in C++?
Possible Duplicate: C++ static constant string (class member) static const C++ class member initialized gives a duplicate symbol error when linking My experience with C++ pre-dated the addition of the string class, so I'm starting over in some ways. I'm defining my header file for my class and want to create a stati...
Move the const std::string MainController::SOME_URL = "www.google.com"; to a cpp file. If you have it in a header, then every .cpp that includes it will have a copy and you will get the duplicate symbol error during the link.
7,571,294
7,571,379
Move value from local stack to heap? (C++)
How can I take an object-as-value result from a method call and place it on the heap? For instance: The Qt QImage::scaledToWidth method returns a copy of the QImage object. Right now I'm doing: QImage *new_img_on_heap = new QImage(old_imgage_on_heap->scaledToWidth(2000)); Is this the only way? Seems like it's goin...
An object is identified by its address. If you want it at another address, you have to construct a new one; you can't move objects. (Even with C++11, the new “move” semantics don't actually move an object; they provide an optimized way of moving its value, if you know that you won't need the value from where you're m...
7,571,326
7,571,378
Why does dividing two int not yield the right value when assigned to double?
How come that in the following snippet int a = 7; int b = 3; double c = 0; c = a / b; c ends up having the value 2, rather than 2.3333, as one would expect. If a and b are doubles, the answer does turn to 2.333. But surely because c already is a double it should have worked with integers? So how come int/int=double d...
This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double. c = a/(double)b;
7,571,357
7,571,430
rand() function in c++
i am not quite sure how this function in c++ works: int rand_0toN1(int n) { return rand() % n; } Another tutorial on internet says to get a random number between a range you need to do something different however, with a being first number in range and n is number of terms in range: int number = a + rand( ) % n; ...
The modulo (remainder) of division by n > 0 is always in the range [0, n); that's a basic property of modular arithmetic. a + rand() % n does not return a number in the range [0, n) unless a=0; it returns an int in the range [a, n + a). Note that this trick does not in general return uniformly distributed integers.
7,571,795
7,571,966
Using Visual C++ with a different C++ compiler?
I like the Visual Studio IDE. I'm used to it and find it is the best IDE I've ever tried. We also find increasing use of C#/.NET here. However, after the underwhelming announcement regarding C++11 features in VS11 I'm looking into replacing the compiler. It seems that the Intel compiler fully integrates with VS but tha...
Depends on how much use you made of the Microsoft-proprietary extensions. Things like #pragma once tend to be supported by all the major compilers, but the weirder COM things (e.g., #import and anything C++/CLI) probably won't be. No idea if MFC will build under the new compiler, but you'll probably have to link it sta...
7,571,907
7,571,941
Using UNICODE character values in C++
How do you use unicode in C++ ? Im aware of wchar_t and wchar_t* but I want to know how you can assign value using only Unicode Values, similar to the way a character can be assigned by equating the variable to the ASCII value: char a = 92; Im uysing the MinGW compiler, if it makes a difference.
Exactly the same way: wchar_t a = 97; wchar_t xi = 0x03be; // ξ
7,571,910
7,571,948
Creating a function in c++ to output to designated source
I want to have a function that outputs certain pieces of information to a specific designated source that is inputted to the function. In code, what I mean is: function output( source ) { source << "hello" << endl; } where source can be a ofstream or cout. So that I can call this function like so: output(cout) or of...
void output(std::ostream &source) { source << "hello" << std::endl; } or even: template <T> void output(T &source) { source << "hello" << std::endl; }
7,571,937
7,572,023
How to delete items from a std::vector given a list of indices
I have a vector of items items, and a vector of indices that should be deleted from items: std::vector<T> items; std::vector<size_t> indicesToDelete; items.push_back(a); items.push_back(b); items.push_back(c); items.push_back(d); items.push_back(e); indicesToDelete.push_back(3); indicesToDelete.push_back(0); indicesT...
I would go for 1/3, that is: order the indices vector, create two iterators into the data vector, one for reading and one for writting. Initialize the writing iterator to the first element to be removed, and the reading iterator to one beyond that one. Then in each step of the loop increment the iterators to the next v...
7,572,104
7,572,306
I *think* I have a memory leak. What now?
I created a C++ DLL function that uses several arrays to process what is eventually image data. I'm attempting to pass these arrays by reference, do the computation, and pass the output back by reference in a pre-allocated array. Within the function I use the Intel Performance Primitives including ippsMalloc and ipps...
To answer your first question, no that's not a memory leak, that's a memory corruption. A memory leak is when you don't free the memory used, and so , the memory usage is growing up. That doesn't make the program to not work, but only end up using too much memory, which results in the computer being really slow (swapin...
7,572,234
7,586,451
Custom CMDIChildWndEx template class linking errors
Ok, I have defined the template class, which compiles as expected, when I implement this class in a function of the CMainFrame of the application and compile it, I receive unresolved linking errors. void CMainFrame::OnFunc() { CTestList<CMyClass> list; } The linking errors: 1>mainfrm.obj : error LNK2019: unresolve...
Your template code is not inlined in the header file. When the template class cpp file is being compiled the compiler doesn't know what instances of T will be required. When your main file is being compiled and you need to instantiate a CTestList the compiler only has the template header file. You need to add a forc...
7,572,328
7,572,435
Chaining calls to temporaries in C++
I have a class that does a transformation on a string, like so class transer{ transer * parent; protected: virtual string inner(const string & s) = 0; public: string trans(const string & s) { if (parent) return parent->trans(inner(s)); else return inner(s); } ...
Temporaries will be destructed at the end of the full expression, in the reverse order they were constructed. Be careful about the latter, however, since there are no guarantees with regards to the order of evaluation. (Except, of course, that of direct dependencies: if you need one temporary in order to create the ...
7,572,529
7,572,600
Complexity of stl deque::insert()
I learned the complexity of deque::insert() from the C++ standard 2003 (chapter 23.2.1.3) as follows: In the worst case, inserting a single element into a deque takes time linear in the minimum of the distance from the insertion point to the beginning of the deque and the distance from the insertion point to the end of...
std::deque is normally (always?) implemented as a collection of chunks of memory, but it won't normally insert a whole new chunk just for you to insert one new element in the middle of the collection. As such, it'll find whether the insertion point is closer to the beginning or end, and shuffle the existing elements to...
7,572,636
7,572,869
LNK2038, iterator mismatch error, need to ignore
I'm getting the linker error LNK2038 when trying to convert a VS2008 project to VS2010. This error occurs when two different projects are compiled in which one is using _DEBUG preprocessor macro, and the other is not. Basically I have a 3rd party library that only has release .libs, so when I try and use that library w...
You must use the same version of the standard library, compiled with the same options, if you expect to successfully link. If you use STLPort, then you can only link with libraries which use the STLPort, not with libraries which use the VC++ standard implementation. If you mix, either you will fail to link, or you wi...
7,573,139
7,573,327
Specializing STL algorithms so they automatically call efficient container member functions when available
The STL has global algorithms that can operate on arbitrary containers as long as they support the basic requirements of that algorithm. For example, some algorithms may require a container to have random access iterators like a vector rather than a list. When a container has a faster way of doing something than the g...
Not in the case of remove_if, since the semantics are different. std::remove_if doesn't actually erase anything from the container, whereas list::remove_if does, so you definitely don't want the former calling the latter. Neither you nor the implementation can literally specialize the generic algorithms for containers ...
7,573,200
7,573,458
to unicode or not to unicode
I'm getting a value from the registry. This value might have double byte characters in it. I will later have to transfer this across the network to a C# client to display. C# is all unicode. The function returns MBCS if you call it non-unicode. What should I use? string result = string(cbData); RegQueryValueExA(h_sub...
Using Unicode whenever possible will make your life easier. The registry contains Unicode natively and converts to MBCS on the fly when you use ReqQueryValueExA, why would you want to do an unneeded conversion? Converting to UTF-8 from UTF-16 might make sense for information going over the network, but if you control b...
7,573,535
7,580,109
llvm Attribute::NoUnwind
i'm running inside http://llvm.org/demo the following snippet: class X { public: ~X() __attribute((nothrow)); }; void a(X* p); void nothr() throw(); void b() { try { X x; a(&x); } catch (X* foo) { nothr(); } } I see that some of the calls, (for instance, to func_llvm_eh_typeid_for) have the Attribute::NoUnwind set: Ca...
It means that you don't have to worry about generating exception handling code or optimizing as if an exception could propagate through that section of code since you've already said it doesn't. If one happens to come through there then it should propagate correctly through to the next stack frame in your program.
7,573,658
7,573,764
C++ template help, using a template for integrations
Hi i'm following a tutorial and video i found online , im trying to make a template to preform a numerical integration of a function where a user can decide which form of integration to preform, im trying to keep it to one file as not to use headers and not use massive ammounts of loops , the code for the first integra...
ans is never assigned a value. That would account for your 1.9147e-307. Did you intend ans = MyCalc.MC(); before the cout ? Also INTG(T a, T b,T n){ INTG::a = a; INTG::b = b; } Is better described as INTG(T a, T b, T n):a(a),b(b),n(n) {} Initializing instead of assigning, and remembering n. So the calcula...
7,573,754
7,611,339
How to use CAPI's CryptImportKey with PEM encode public key from OpenSSL?
How do I get the Microsoft's CryptoAPI CryptImportKey function to import a PEM encoded key? It actually works but CryptDecrypt returns an error. // 1. Generate a Public/Private RSA key pair like so: openssl genrsa -out private.pem 2048 openssl rsa -in private.pem -out public.pem -outform PEM -pubout // 2. Create a di...
You are using the wrong APIs. RSA_sign() signs a hash; use CryptVerifySignature() to verify it.
7,573,769
7,573,816
What is the right way to put objects to boost::property_tree?
Consider following example: #include <boost\property_tree\ptree.hpp> #include <boost/any.hpp> typedef boost::property_tree::ptree PT; struct Foo { int bar; int egg; Foo(): bar(), egg() {} }; int main() { Foo foo; foo.bar = 5; PT pt; pt.put<Foo>("foo", foo); return 0; } I'm new to bo...
Simply create an overloaded operator<< for your Foo object-type. This can be done by creating a function that takes the members of your Foo object-type, and passes them via the operator<< to a ostream object-type. Here is a very simple example: ostream& operator<<(ostream& out, Foo output_object) { out << egg << ...