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 |
|---|---|---|---|---|
4,200,595 | 4,200,611 | Possible to compile any .c file in isolation (that is, without a main?) | I currently have a "library-like" .c file (that'll be shown below). I have 2 questions about it:
If I want to see if it compiles well for itself, how can I do it? If I try to gcc it, it will always give a "no main" error, which makes sense, but raises the problem of knowing if a given .c file will compile well or not ... | To compile it without linking (doesn't require a main entry point):
cc -c file.c -o file.o
Even for a small file that defines routines that will be called from other source files you still want a header file. The header file is how the compiler knows the interface to the routines before the linker ties it all together... |
4,200,760 | 4,201,942 | How can I monitor QProcess finished() in qt4 (Signal/Slot) | It looks as if their was a solution for this in qt3, but I cannot find one for qt4 (all I have used, goggling I saw solutions for qt3).
connect(r, SIGNAL(readyReadStandardError()), this, SLOT(updateError()));
connect(r, SIGNAL(readyReadStandardOutput()), this, SLOT(updateText()));
connect(r, SIGNAL(finished(int exitcod... | replace your code line
connect(r, SIGNAL(finished(int exitcode)), this, SLOT(updateExit()));
with
connect(r, SIGNAL(finished(int)), this, SLOT(updateExit()));
When connection signals and slots dont give a parameter name.
|
4,200,813 | 4,209,619 | std::once_flag equivalent of BOOST_ONCE_INIT | I'm working with some code I borrowed from here which uses boost::call_once to make a singleton class, and would like to convert everything to use C++0x's std::call_once to remove the dependency on Boost. Does anyone know what the Std equivalent of BOOST_ONCE_INIT is?
| std::once_flag has a constexpr constructor, so instances with static storage duration are always statically initialized.
Incidentally, the point about scoped_ptr is important --- the constructor of the scoped_ptr instance is NOT static initialization, so will race with any uses of the singleton before it has been initi... |
4,200,904 | 4,200,976 | C++ - Compiling error on a tree homework : error: expected constructor, destructor, or type conversion before ‘*’ token | I'm currently trying to do a homework, and I'm trying to get my things to compile at first (class headers in the .h file, and the empty definitions in the .inl file (I'm using the typename template)).
I'm getting this error :
error: expected constructor, destructor, or type conversion before ‘*’ token
Here's my .h fil... | Try to qualify as so while defining in .inl file (and not the header file as per your concern).
The return type needs to be looked up in the proper scope appropriately.
BRAIN COMPILED CODE AHEAD
template<typename E>
typename Arbre<E>::Noeud * Arbre<E>::_auxPereSym(E *tabS, int debut, int fin, E **ptr, int &card) throw ... |
4,201,129 | 4,277,319 | Compiling in Eclipse with gcc's -lpthread and -lrt set | I am currently trying to use Eclipse to develop some code that I've been doing in a text editor in C.
I am currently under Linux, compiling it with GCC with the following arguments:
gcc -o SO SO.c -lpthread -lrt
I've tried adding "-lpthread -lrt" to Eclipse's "C/C++ Build"->"Discovery Options"-> "Compiler Invocation A... | In the project properties, go to : C/C++ Build --> Settings.
Then "Tool Settings", select "Libraries" under "Linker".
You can add all your project libraries there (without the "-l"). Also in the lower part, you can add custom path to search libraries.
|
4,201,175 | 4,206,417 | Why can't I parse a XML file using QXmlStreamReader from Qt? | I'm trying to figure out how QXmlStreamReader works for a C++ application I'm writing. The XML file I want to parse is a large dictionary with a convoluted structure and plenty of Unicode characters so I decided to try a small test case with a simpler document. Unfortunately, I hit a wall. Here's the example xml file:
... | I'm answering this myself as this problem was related to three issues, two of which were brought up by the responses.
The file actually wasn't UTF-8 encoded. I changed the encoding to iso-8859-1 and the encoding warning disappeared.
The text() function doesn't work as I expected. I have to use readElementText() to re... |
4,201,179 | 4,203,702 | getting texture picture for opengl through resource file(c++/visual studio 2008) | when you create a new opengl project in visual studio 2008, you get three folders: one for header files, one for source files and one for resource files.
Is it feasible to put a jpg picture in resource files and then link to it to load it as a texture?
i want to load jpg pictures as textures, but i want to do that thro... | I believe If you link the texture as a resource, it will be stored inside your .exe file. That's not a commonly used solution - usually you'd want to store resources in a separate folder (or an archive/VFS file) next to your .exe - then the texture will be loaded from this file after you run your program. This also mea... |
4,201,197 | 4,201,411 | Which compiler(s) have the most advanced support for the current state of C++0x? |
Possible Duplicate:
Compiler support for upcoming C++0x
Looking to use it for a purely experimental purposes. Is there any out there that has full support? Seems VC++ and GCC have very good support, but still incomplete (understandably).
| As previously stated by Travis Gockel, GCC is the compiler with best support for C++0x.
The best source to compare the availability of C++0x features by compilers is this chart that is maintained by Scott Meyers: http://www.aristeia.com/C++0x/C++0xFeatureAvailability.htm
|
4,201,232 | 4,201,242 | Dealing with std::List in std::Map for operator==,operator!= etc | I am trying to understand Directed Graph implementation (without Boost library that is mentioned alot),just trying to learn things in c++. Here is what I came up with reading various pointers on different questions. I figured I could use a map to look up certain places within the graph and a list to hold the links toge... | To test whether a key exists in a map, you should use the member function find(). When you use operator[] like you describe, you end up inserting elements into the map that shouldn't be in the map (it's effectively garbage data, right?)
The find() member function returns an iterator to the element with the key you giv... |
4,201,383 | 4,201,517 | hash_map is saving each key/val pair even when keys are equal | Hey guys, I am using a hash_map to relate strings to one another, with this code:
#include <string>
#include <iostream>
#include <hash_map>
using namespace std;
using namespace stdext;
struct StrCompare : public stdext::hash_compare<string> {
unsigned int operator()(const string str) const {
unsigned int hash = 0;... | From some of the details of your example, it looks like you're using MSVC. Microsoft's hash_map uses a comparison function that works in conjunction with the hash function to provide an ordering for keys that hash to the same value. This is different than SGI's specification of hash_map. Specifically (from http://msdn... |
4,201,399 | 4,201,438 | Prompting a user with an input box? [C++] | My goal is to simply use a pop-up box to ask the user for an input. I've searched around quite a bit and pretty much all the results say that creating a messageBox is really easy:
MessageBox (NULL, "Hello World" , "Hello", MB_OKCANCEL);
But that creating a pop-up that takes input is more involved and there isn't a str... | There is nothing like that for pure C++. Basically what you're trying to do can only be achieved by using an API call to the OS or by using some GUI library like Qt (which I recommend cause it's waaaaay easier then calling native APIs and it's also multi-platform)
Using Qt you can show an input dialog pretty much the s... |
4,201,481 | 4,201,694 | FFMPEG with QT memory leak | Let me start with a code clip:
QByteArray ba;
ba.resize(500000);
int encsize = avcodec_encode_video(context, (uint8_t*)ba.data(), 500000, frame.unownedPointer());
What I'm doing is encoding the data from frame and putting the data into the buffer pointed at QByteArray. If I comment out the avcodec_encode_video line m... | Take a look at the code for QtFFmpegwrapper it uses a saved context to do this efficently, or you can just use the QtFFMpegwrapper directly
|
4,201,498 | 4,201,595 | Store settings of qt application using QSettings | Hello I have created an application using qt and I managed to save some of its settings using QSettings.
void DoneIt::writeSettings()
{
QSettings settings("mycompany", "RightDoneIt");
settings.beginGroup("DoneIt");
settings.setValue("size", size());
settings.setValue("pos", pos());
settings.endGroup... |
Put them to QButtonGroup.
Use QButtonGroup::setId to set Id for each radio button in this group.
Save the Id of the checked button get by QButtonGroup::checkedId.
Get the pointer of this button using QButtonGroup::button(id) when restore, and call QAbstractButton::setChecked.
BTW: if you want to saves the current sta... |
4,201,524 | 4,201,545 | Conceptual problem in Union | My code is this
// using_a_union.cpp
#include <stdio.h>
union NumericType
{
int iValue;
long lValue;
double dValue;
};
int main()
{
union NumericType Values = { 10 }; // iValue = 10
printf("%d\n", Values.iValue);
Values.dValue = 3.1416;
printf("%d\n", Values.iValu... | In a union, all of the data members overlap. You can only use one data member of a union at a time.
iValue, lValue, and dValue all occupy the same space.
As soon as you write to dValue, the iValue and lValue members are no longer usable: only dValue is usable.
Edit: To address the comments below: You cannot writ... |
4,201,728 | 4,202,250 | BringWindowToTop is Not working even if I get the handle to Class Window | I am registering my Class in the following method:
BOOL CNDSClientDlg::InitInstance()
{
//Register Window Updated on 16th Nov 2010, @Subhen
// Register our unique class name that we wish to use
WNDCLASS wndcls;
memset(&wndcls, 0, sizeof(WNDCLASS));
wndcls.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRA... | A few things to look at...
1) Try SetForegroundWindow() instead of BringWindowToTop(). It's been awhile since I've done Win32 programming, but I seem to recall that BringWindowToTop() has some limitations (especially when working with windows in different processes).
2) There are some rules that Microsoft put in place... |
4,201,856 | 4,201,966 | Error handling strategies in a shared library - C | I am writing a cross platform shared library (.so in linux and .dll in windows) using C. Currently when there is a error, library functions returns the proper error code and writes error information into the stderr. Library functions also emits some information and debug messages to stdout. This works well for console ... | Best practice (IMHO) is for a library to not print anything to stderr (or stdout), because they may not even be present. In addition to the GUI situation, you also have the use case of a server application that doesn't have a "console", and may want to be logging errors using a function like syslog().
Some approaches f... |
4,201,862 | 4,203,177 | Browse folders and add their files to a list with qt | Hello Great community of SO!
I have created a GUI application with qt and I added a QTreeWidget and a 2 buttons (add and delete) in my main window.
Is it possible to find examples of code in order to learn how to add and delete files to this QTreeWidget ?
I would like to display their size, name and location into the... | For directory browsing try QDir.
To create and remove files use QFile.
Quite a lot of examples and tutorials can be found here Qt documentation.
Just select your release.
|
4,201,893 | 4,201,910 | error C2446: == : no conversion from const char * to TCHAR * | I have a TCHAR define below:
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
and I want to comapare as below:
if(szProcessName == "NDSClient.exe")
{
}
But then I am getting the errors:
error C2446: == : no conversion from const char * to TCHAR *
error C2440: '==' : cannot convert from 'const char [14]' to 'TC... | "NDSClient.exe" is a const char* string on windows. If you want it to become a const TCHAR* then you need to use the TEXT macro. Also, you can not compare strings using == use a equivalent TCHAR function such as _tcscmp.
|
4,202,010 | 4,435,322 | DirectX 10 Draw Text to texture | I am atempting to draw text to a textured mesh object. The mesh is basically a cube which has been pasted up to the front of the screen. (overall I'm aiming for a menu system). After a bit of googling I've found surprisingly little information on how to draw a text to a texture. I've read that it should be as simple as... | When you need to render text into texture, you should setup rendering to texture as Adam suggested, to actually render some text you can do this
Create font and sprite
D3DX10CreateFont(device, 16, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_TT_ONLY_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Verdana", &f... |
4,202,015 | 4,203,063 | To print data to a file | I have overloaded << operator such that it write to file and also on the console. I have created 8 threads to the same function, and I want to output
hello
hi
If I run this thread routine in an infinite loop the o/p in the file is
hello
hi
hello
hi
hello
hi
ello
i
hello
hi
hello
hi
llo
i
hello
hi
This has no patte... | Create a queue and write to it. Dequeue queue in desired granularity - one line for example (I guess that that's what you want from your example).
Something like:
CRITICAL_SECTION cs;
list<string> _queue;
void Write(string line)
{
EnterCriticalSection(&cs);
_queue.push_back(line);
LeaveCriticalSection(&c... |
4,202,274 | 4,202,288 | Calling a constructor | Take a scenario as shown below:
Class A : public B
{
private:
C obj
public:
A()
}
Class B
{
B(int , int)
}
Class C
{
C();
C( int , int)
}
Is there a way by which I can call the non default constructor when initialising an object of Class A?
I know that to initialize B, I could do something like:
A():B(int, int) /... | Both base classes and data members can appear in the initializer list:
A() : B(42, 42), obj(42, 42) { }
|
4,202,455 | 4,202,471 | Is it worth learning C/C++ before learning Python? | I want to learn python, but I feel I should learn C or C++ to get a solid base to build on. I already know some C/C++ as well as other programming languages, which does help. So, should I master C/C++ first?
| In my opinion it's better to start learning Python.
I found it easier to learn then C or C++. It has libraries to do virtually anything you might need, and can do essentially anything.
The only reason to use a more difficult language like C/C++ is if you need the performance or are writing code for an embedded system.... |
4,202,627 | 4,202,929 | Extending Python with C++ no SWIG | OK so I have a C++ function with a header like this:
int myfunc(vector<int> a, vector<mystruct> b, vector<int> c)
I have written the wrapper code (using Python.h as I have done many times with C, which translates the Python data types into the vector datatypes and structs I use in my program). The problem is I don't k... | You should add language="c++" to your Extension object:
Extension("MyModule", ["myfunc.cpp"], language="c++")
|
4,202,656 | 4,202,827 | OpenCV RGB values in hex? | So I've successfully access pixel data in a frame using the c++ frame access wrapper on the opencv webpage
template<class Frame>
class Frame_Data {
IplImage *imgp;
public:
Frame_Data (IplImage *img=0) {imgp = img;}
~Frame_Data () {imgp = 0;}
void operator=(IplImage *img) {imgp=... | The range from 0x00 ... 0xFF that you are seeing is one byte which can hold a value between 0 and 255 which is how pixel color data is stored, generally in 3 or 4 bytes consisting of Red, Blue, Green and optionally Alpha.
The CvScalar is just a convenience container of 1, 2, 3 or 4 doubles which can be used to hold the... |
4,202,687 | 4,203,005 | Using Assembly Language in C/C++ | I remember reading somewhere that to really optimize & speed up certain section of the code, programmers write that section in Assembly language. My questions are -
Is this practice still done? and How does one do this?
Isn't writing in Assembly Language a bit too cumbersome & archaic?
When we compile C code (with or... | The only time it's useful to revert to assembly language is when
the CPU instructions don't have functional equivalents in C++ (e.g. single-instruction-multiple-data instructions, BCD or decimal arithmetic operations)
AND the compiler doesn't provide extra functions to wrap these operations (e.g. C++11 Standard has a... |
4,202,877 | 4,202,923 | typeid for polymorphic types | I expected this code to print 'Same 1' and 'Same2', but it prints only 'Same1':
#include <iostream>
#include <typeinfo>
using namespace std;
struct C{virtual ~C(){}};
struct D : C{};
int main(){
D d;
C c, &cr1 = d;
if(typeid(cr1) == typeid(D)) cout << "Same1";
if(typeid(&cr1) == typeid(D*)) cout << "Same2"... | Pointers aren't polymorphic types. They don't have virtual members. In fact, they have no members whatsoever. They also cannot derive from other types, nor be used as base classes. Hence, the static and dynamic type of a T* is always T*.
In your "Same2" line, you're comparing the typeid of a pointer, not the pointed-to... |
4,202,937 | 4,202,985 | How to implement a protocol | are there any open source desktop sharing protocols? if so, what are they? can anybody tell me the things i would know in order to implement a protocol e.g if i want to write a desktop sharing protocol what are the things i need to know and from where i should begin.(preferred languages Java, C++ and C#)
Thanks !!
| RFB is the protocol used in VNC applications, and it is an open specification.
A protocol is just a language that networked applications 'agree' to speak. That is to say, because both ends of the connection are speaking the same language (meaning they know what bytes mean what in the communication) they are capable of ... |
4,203,010 | 4,203,154 | How to initialize member-struct in initializer list of C++ class? | I have the following class definitions in c++:
struct Foo {
int x;
char array[24];
short* y;
};
class Bar {
Bar();
int x;
Foo foo;
};
and would like to initialize the "foo" struct (with all its members) to zero in the initializer of the Bar class. Can this be done this way:
Bar::Bar()
: foo(),
x(8)... | First of all, you should (must !) read this c++ faq regarding POD and aggregates. In your case, Foo is indeed a POD class and foo() is a value initialization :
To value-initialize an object of type
T means:
if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor
fo... |
4,203,034 | 4,204,750 | Unit testing with boost::statechart | We are using the boost statechart library and have troubles writing unit tests for the code.
In our normal execution the state machine starts in ClosedState:
struct BoostStateMachine : sc::state_machine<BoostStateMachine, ClosedState >
We would like to test a specific state transition without having to traverse the st... | I'll admit it's not great, but
#ifdef DEBUG
typedef AnotherState StartingState;
#else
typedef ClosedState StartingState;
#endif
struct BoostStateMachine : sc::state_machine<BoostStateMachine, StartingState > {...
EDIT addressing comment
#ifndef INITIAL_STATE
#define INITIAL_STATE ClosedState
#endif
struct BoostStateMa... |
4,203,079 | 4,203,151 | Can I use Find window without using RegisterClass and CreateWindow | I am trying to bring my running application on click of windows rightclick. Please note I dont want a new instance of the same application but bringing the same application to the front by using SetForegroundWindow
I have tried using AfxRegisterClass and Createwindow (Previos post here) but this creates a new window an... | Probably better to use mutexes, but yes, you can use FindWindow for that. Something like this:
HWND hwnd = FindWindow(NULL, "My App's Hopefully Unique Title");
if (hwnd)
{
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
SetFocus(hwnd);
}
|
4,203,095 | 4,203,170 | C++: Error: Unable to create variable object | I have a simple method:
std::vector<string> start()
{
std::vector<std::string> deletedFiles; // << error appeared at this declaration
}
Error: Unable to create variable object
What is wrong here?
Thanks in advance.
| This similar program compiles without a hitch:
#include <vector>
#include <string>
std::vector<std::string> start()
{
std::vector<std::string> deletedFiles;
return deletedFiles;
}
int main()
{
std::vector<std::string> deletedFiles = start();
return 0;
}
Please double check your #includes and your std... |
4,203,122 | 4,211,586 | QT : Cannot find moc file | I'm trying to create a test application in QT to test another QT application's UI using qtlib. I learned that you also need to use QTEST_MAIN() macro which expands to a simple main() method that runs all the test functions.
QTEST_MAIN(TestAppUI)
#include "testapp.moc"
I'm compiling it using "make" and somewhere in m... | I just figured what's wrong. I needed to add ${QT_LIBRARIES} ${QT_QTTEST_LIBRARY} in TARGET_LINK_LIBRARIES ... :) and remove #include "testapp.moc"
|
4,203,365 | 4,209,275 | Visual Studio 2010 vs Visual Studio 2005 for C++ | My department writes a mixture of Windows, Linux and cross platform (RHEL Linx and Windows Server 2003) C++ code for in house applications. We use the STL and Boost 1.39.
VS2010 is now available in my organisation. If we were to move to VS2010 I'd have to make a significant business case for it. What would some of t... | If you're only interested in IDE improvements, and you make a big use of smart pointers, I'd suggest to wait up to SP1 (or some SP that comes with fixes to intellisense).
As some people pointed out, there are BIG changes in C++ intellisense, to support a lot of features that other languages already had for years. The t... |
4,203,406 | 4,203,569 | Will WaitForSingleObject cause a context switch when waiting with a timeout time of zero? | Will WaitForSingleObject (or WaitForMultipleObjects) cause a context switch when waiting for an event with a timeout time of zero? (Sleep(0) will yield a threads time-slice immediately as far as I know.)
Now, regarding WaitForSingle|MultipleObject and Event handles. If WaitFor*Object actually needs to wait, it would ob... | Based on the Windows Research Kernel and some simple reverse-engineering of KeWaitForSingleObject, the answer is no. Looking at the WRK, the internal timer's due time is checked before KiSwapThread is called, making sure the function returns immediately if the object isn't signaled.
|
4,203,467 | 4,219,454 | Multiple-readers, single-writer locks in Boost | I'm trying to implement the following code in a multithreading scenario:
Get shared access to mutex
Read data structure
If necessary:
Get exclusive access to mutex
Update data structure
Release exclusive lock
Release shared lock
Boost threads has a shared_mutex class which was designed for a multiple-readers,... | boost::shared_lock doesn't help in this situation (multiple readers that can become writers), since only a single thread may own an upgradable lock. This is both implied by the quote from the documentation in the question, and by looking at the code (thread\win32\shared_mutex.hpp). If a thread tries to acquire an upgra... |
4,203,479 | 4,203,641 | dynamic_cast confusion | I give up on this...
$5.2.7/2- "If T is a pointer type, v
shall be an rvalue of a pointer to
complete class type, and the result is
an rvalue of type T. If T is a
reference type, v shall be an lvalue
of a complete class type, and the
result is an lvalue of the type
referred to by T."
In accordance with ... | "Otherwise" in this case means, "unless the conditions in 5.2.7/5 apply".
You can tell this because /2 places a requirement on the program regarding the operand of the the dynamic_cast (note the "shall" language of "v shall be an lvalue" vs. the "is" language of "the result is an lvalue"). In common with other places i... |
4,203,487 | 4,204,703 | Implementing a bare-bones COM object | I need to implement a bare-bones COM object in straight C++ (no ATL) that is used by a legacy web application to check that my application exists. The web application does something like this (JavaScript):
var object = new ActiveXObject("My.Application");
I want to ensure that the above succeeds but thats all I need t... | It's not sufficient to build a bare-bones COM object. For starters, that would be so bare-bones that there's no name associated with it. You've already discovered that you need an object factory, too.
So, yes, implement DllGetClassObject. You'll have to check the input rclsid argument. This is an interface identifier. ... |
4,203,503 | 4,204,399 | Getting/deducing type in template-function for return value | I am using the Boost Graph Library and have build my own classes upon that.
Now, I have the following function:
template< class VERTEXPROPERTIES >
VERTEXPROPERTIES& properties(const Vertex& v) const
{
typename property_map<FilteredGraphContainer, vertex_properties_t>::const_type param = get(vertex_properties, gr... | Again, my apologies for not providing more information.
It seemed to me that the compiler was not able to deduce the dependant type there. I encountered this issue some times before when working with templates.
I will provide the fix here in case somebody might encounter similar issues.
The FilteredGraph uses an instan... |
4,203,553 | 4,204,142 | Access to TCP statistics/information per socket possible? (C/C++) | I require some informations like the amount of resend packages/packet-loss occurred for a specific TCP-Socket I created. Does somebody know a way how to access or request such informations directly from my C/C++ program? Maybe something Linux specific?
Or do I need (as a workaround) to capture and analyze my own traffi... | By using getsockopt() to get or setsockopt() to set TCP socket options, you can use TCP_INFO option on linux machines in order to get information about a socket. This option should be avoided if you want the code to be portable.
What you will get back is a struct tcp_info from the kernel that contains information such ... |
4,203,591 | 4,203,649 | Why there is a convention of declaring default namespace/libraries in any programming language? | Why don't any programming language load the default libraries like stdio.h, iostream.h or using Systemso that there declaration is avoided?
As these namespace/libraries are required in any program, why the compilers expect it to be declared by the user.
Do any programs exist without using namespace/headers? even if yes... | It's because there are programs which are written without the standard libraries. For example, there are plenty of C programs running on embedded systems that don't provide stdio.h, since it doesn't make any sense on those platforms (in C, such environments are referred to as "freestanding", as opposed to the more usu... |
4,203,601 | 4,204,481 | C++: boost/filesystem: some questions | I am using Boost library in C++ running in Ubuntu enviroment. I have some questions that I am not clear about:
fs::is_directory
namespace fs = boost::filesystem;
fs::path full_path(fs::initial_path<fs::path>() );
full_path = fs::system_complete(fs::path( "temp/"));
if(fs::is_directory(full_path ))
{
cout << "... |
Seems like that should work. Why don't you put a cout << fullpath before the if to make sure the path really contains what you think it does?
I've never used last_write_time. Can't help you with that one.
You have to iterate over the directory's contents and use fs::is_directory(dir->status()) to determine whether a g... |
4,203,683 | 4,203,929 | Finding all callers of a function from the object file | What are the ways to find all callers (symbol names) of a particular function / symbol using only the compilation unit? How to find from a compilation unit which library included in that unit was a symbol defined in?
| If you're looking for calls to a function called func in an object file called obj.o, then:
objdump -dCS .text obj.o | grep func
Obviously, you can't find incoming calls this way.
|
4,203,690 | 4,203,721 | What do we need unary_function and binary_function for? | I read the tutorials about the binary and unary functions. I understood the structure of them, but I couldn't imagine in which case I need these functions. Can you give an example for usage of them.
http://www.cplusplus.com/reference/std/functional/unary_function/
http://www.cplusplus.com/reference/std/functional/bina... | These aren't functions, these are classes (structs, actually, but doesn't matter). When you define your own binary functions to use with STL algorithms, you derive them from these classes in order to automatically get all the typedefs.
E.g.
struct SomeFancyUnaryFunction: public std::unary_function<Arg_t, Result_t>
{
... |
4,203,724 | 4,205,890 | Performance gains in re-writing C# code in C/C++ | I wrote part of a program that does some heavy work with strings in C#. I initially chose C# not only because it was easier to use .NET's data structures, but also because I need to use this program to analyse some 2-3 million text records in a database, and it is much easier to connect to databases using C#.
There was... | First, profile your code. You might find some real headsmacker that speeds the C# code up greatly.
Second, writing the code in C using pointers is not really a fair comparison. If you are going to use pointers why not write it in assembly language and get real performance? (Not really, just reductio ad absurdam.) A... |
4,204,172 | 4,204,212 | GetInterfaceFromGlobal() call fails with an out-of-process COM server in Visual Studio 2010 | I have an Out-of-process COM server executable which was developed using Visual Studio 6.0 and it has been working fine for the past 10 years. Now I converted this project to Visual Studio 2010 and encountered a problem with GetInterfaceFromGlobal().
I'm using the GIT to hold IDispatch pointers to each of my COM client... | Don't touch that constant - just ignore the change. _DEFAULT_VECTORLENGTH controls how CComDynamicUnkArray::Add() works and your code that traverses the CComDynamicUnkArray object should just skip the null pointers stored inside.
Something like this:
for( int i = 0; i < array.GetSize(); i++ ) {
IUnknown* pointer = ar... |
4,204,186 | 4,204,528 | How to use gcov with QMake for code coverage | I would like to use gcov with my unit test written using QTestLib. I have managed to generate some .gcno files along my object files by adding this to my .pro file :
QMAKE_CXXFLAGS += -fprofile-arcs -ftest-coverage -O0
But, when I run :
gcov main.cpp.gcno
I got a bunch of .gcov files generated with non-useful conten... | Have you run your QT program? Until then there's no coverage data.
Also, have a look at lcov, which you can use to get a nice html-based report of everything
|
4,204,239 | 4,205,558 | Making a Objective-C Wrapper for a C++ Library | I am trying to make a wrapper in Objective-C so I don't have to write c++ outside the library classes.
The Library main file is LLAHProcessor.h .cpp
My Wrapper is LLAHProcessorWrapper.h .mm
It compiles fine, but when I add LLAHProcessorWrapper to other class, (Lets say an UIView) as a member variable I get hundreds of... | Your problem is that .m files are compiled as C instead of C++. Thus when the compiler comes across any C++ even in a header file while compiling a .m file, it will barf.
No doubt you have to put some C++ in your header file because your Objective C object wraps a C++ object, but there are ways around this. One way w... |
4,204,310 | 4,204,462 | Which structure is best for implementation when the number of elements in a list/array is variable? | I have a slightly specific question. I am using C/C++ with OpenCV. My aim to store detected rectangles in a list/array style structure. However, the length is variable for every frame (iteration).
What should I use to store this info? I thought of Linked Lists, however, they are slow to traverse and also if the number... | I would recommend you to use std::vector. The elements in a std::vector are guaranteed by the C++ Standard to be contiguous, just like a C array would be. This allows std::vector to be the interface between C++ data structures and C functions. You can use std::vector<T>::resize to make sure there is space allocated bef... |
4,204,488 | 4,204,525 | Marshalling a VARIANT back from COM to C++ client | I'm attempting to marshal a safearray of BSTRs from a COM object, back to a C++ client application.
My IDL definition of the function involved:
[id(5), helpstring("method GetStreams")]
HRESULT GetStreams( [out,retval] VARIANT* pvarStreamNames );
Here's my implementation of the GetStreams() function:
STDMETHODIMP ... | There're two problems. The first one is
VARIANT varStreamNames;
is unitialized, so when
varOutNames.Detach(pvarStreamNames);
runs it calls VariantClear() on an uninitialized variable and this leads to undefined behavior - your program crashes.
You have to call VariantInit() on varStreamNames before invoking the COM ... |
4,204,530 | 4,204,579 | c++ toupper - standard function? |
Possible Duplicate:
Convert a String In C++ To Upper Case
Hi,
I need a portable function to convert string in c++ to upper case. I'm now using toupper( char); function. Is it a standard function? If not, what it's the correct way to do it across platforms? Btw, is there any web / wiki where I can list all c++ standa... | Yes, toupper is declared in the cctype header. You can transform a string with an algorithm:
#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string str("hello there");
std::cout << str << '\n';
std::transform(str.begin(), str.end(), str.begin(), std::toupper)... |
4,204,540 | 4,205,276 | Invoke C++ method from VB.Net with string handled as string array | I have a C++ method with this signature:
STDMETHODIMP ClassName::FunctionName(long number, BSTR* names, long* status)
Inside the method the names variable is accessed as an array of strings, i.e.
char * tempString = NULL;
for (int n = 0; n < number; n++)
{
tempString = OLE2T(names[n]);
...
I compile the C++ pro... | Nope, [size_is] is an attribute that only midl.exe knows how to use. It does so when it generates the proxy/stub for the interface, something that's used when you want to make the call across process boundaries.
It isn't otherwise expressible in a type library. The argument gets emitted as "pointer to BSTR" which cou... |
4,205,050 | 4,205,071 | Inheriting and overriding functions of a std::string? | Since std::string is actually a typedef of a templated class, how can I override it? I want to make a UTF-8 std::string that will return the correct length, among other things.
| DON'T DERIVE FROM STRING
std::string, that is, basically the whole basic_string template is not designed to be derived from. There are zillions of articles about that already. It doesn't have any virtual functions so there is nothing to override. The best you can do is hide something. Best is to use composition/aggrega... |
4,205,194 | 4,205,318 | QNetworkAccessmanager vs cURL for ftp upload | I have written a simple ftp uploader in C++ with qt using QNetworkAccessManager's put request
its is working as it should but im not happy with the upload speed i get.
i utilize 80% of my upload line while with filezilla i get 100%
The problem is (at least thats what i think) that Qt using only one connection to upload... | cURL allows multi sessions whereby it can perform multiple transfers concurrently.
Cannot really comment though on whether it is fast. The network interaction is likely to be your bottleneck whichever you use.
|
4,205,577 | 4,206,111 | OpenCV 640x480 standard size? | Quick easy question, why is 640x480 always the standard window width/height when getting a webcam stream? is this because most webcams have a viewable area of this size in pixels?
| Almost all common webcams use a cheap image sensor, and by far, the most common sensors available on the market are available in two sizes: 320x240 (QVA) or 640x480 (VGA). Other types of sensors are uncommon at best, because they tend to be of either or both higher quality or simply more expensive to manufacture.
It's ... |
4,205,720 | 4,206,815 | Iterating over a vector in reverse direction | I need to iterate over a vector from the end to the beginning. The "correct" way is
for(std::vector<SomeT>::reverse_iterator rit = v.rbegin(); rit != v.rend(); ++rit)
{
//do Something
}
When //do Something involves knowing the actual index, then some calculations need to be done with rit to obtain it, like index =... | As you've noted, the problem with a condition of i >= 0 when it's unsigned is that the condition is always true. Instead of subtracting 1 when you initialize i and then again after each iteration, subtract 1 after checking the loop condition:
for (unsigned i = v.size(); i-- > 0; )
I like this style for several reasons... |
4,205,809 | 4,205,838 | What is difference between TCHAR and WCHAR? | I've opened winnt.h header file and found there this two lines:
typedef wchar_t WCHAR;
and
typedef WCHAR TCHAR, *PTCHAR;
but there was comment in one of my posts that there is some difference between them. Then what is the difference?
| If you read the entire header, you will find:
#ifdef _UNICODE
typedef WCHAR TCHAR;
#else
typedef char TCHAR;
#endif
or words to that effect.
Perhaps MS has removed the narrow option of late.
|
4,205,812 | 4,205,882 | Will these two methods of accessing the array implemented identically or not? | We have a three-byte array like below:
char charArray[3];
charArray[1]='a';
//or
char * charP=charArray;
charP[1]='a';
Two methods are used to access to second element of array, now will they be implemented in the same way by compiler or the first method will not involve a pointer like second method?
|
will they be implemented in the same way by compiler
Maybe.
If you use the name of an array and the subscript is a constant expression, a compiler can probably do some or all of the pointer arithmetic at compile-time. It might not be able to do the same using a pointer to an array; that probably depends on whether o... |
4,206,041 | 4,206,085 | Getting Vertex_handles to the points of a delaunay triangulation | I want to iterate through all vertices of a CGAL::Delaunay_triangulation_2, but am unable to find documentation about getting all the vertex handles.
The documentation I found for this explained how to iterate through the triangulation.
typedef CGAL::Delaunay_triangulation_2<K> T;
typedef T::Vertex_handle Vh;
typedef T... | Okay I was just stupid. Tried some more random things and got that the iterator actually is the handle. Of course I find this out after writing the whole post here :-)
typedef CGAL::Delaunay_triangulation_2<K> T;
typedef T::Vertex_handle Vh;
typedef T::Vertex_iterator Vi;
for (Vi vi = g.vertices_begin(); vi != g.ver... |
4,206,349 | 4,208,349 | how boost multi_index is implemented | I have some difficulties understanding how Boost.MultiIndex is implemented. Lets say I have the following:
typedef multi_index_container<
employee,
indexed_by<
ordered_unique<member<employee, std::string, &employee::name> >,
ordered_unique<member<employee, int, &employee::age> >
>
> emp... | A short explanation on the underlying structure is given here, quoted below:
The implementation is based on nodes interlinked with pointers, just as say your favorite std::set implementation. I'll elaborate a bit on this: A std::set is usually implemented as an rb-tree where nodes look like
struct node
{
// header
... |
4,206,376 | 4,206,498 | PHP or CGI - Convert .ico to gif or png or jpg? | How do you convert a favicon.ico to a regular web-accessible graphics - gif, png, or jpg using PHP or C/C++/CGI?
Are there methods that do not require ImageMagick?
| If your server doesn't have Imagick installed, you can use GD (the hard way). You can do a pixel-by-pixel mapping by using the following format for sniffing the actual bitmap: http://www.daubnet.com/en/file-format-ico
|
4,206,381 | 4,212,710 | OpenCV cvSet2d.....what does this do | I was browsing over some code in the OpenCV page when it came to accessing Pixel Data
IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3);
CvScalar s;
s=cvGet2D(img,i,j); // get the (i,j) pixel value
printf("B=%f, G=%f, R=%f\n",s.val[0],s.val[1],s.val[2]);
s.val[0]=111;
s.val[1]=111;
s.val[2]=111;
cvSet2D(img,... | The cvSet2D(img, i, j, s) functions to not access the (i,j)th pixel. It accesses the (j,i)th pixel. That is because images are stored as a matrix - you need to specify the row first (the Y coordinate) and then the column (the X coordinate).
Instead of using the cvGet/Set functions, did you try using pointers to access ... |
4,206,463 | 4,323,419 | Polymorphic Explicit Template Instantiation | Have this basic hierarchy:
// header
class Base
{
virtual void method() { }
virtual ~method() { }
};
class Subclass : Base
{
virtual void method() { }
virtual ~method() { }
};
I wish to subclass Base with two explicit variations (without having to provide two implementations of Subclass if possible),... | Brief summary of the problem and solution:
To use a method from a templated base class requires either using the template parameter:
T::method();
or simply using "this" to allow it to be found without explicitly knowing the template parameter:
this->method();
Thanks to those that pointed me towards finding this solut... |
4,206,524 | 4,206,550 | error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::vector<_Ty> *' (or there is no acceptable conversion) | I've got the following when building a graph.
#include <vector>
using namespace std;
template<class T>
class Node
{
private:
T data;
Node<T> *link;
vector<T> neighbors;
public:
Node(){neighbors = new vector<T>();};
};
int main()
{
Node<int> n;
return 0;
}
... which returns the error C2679: binary '=': ... | The new operator returns a pointer type, but your member variable neighbors is not a pointer. So you're assigning a pointer (the result of new) to a non-pointer type. Your neighbors variable needs to be a pointer: vector<T>* neighbors.
But I think you're probably misunderstanding the use of new here. You probably sh... |
4,206,570 | 4,309,141 | One mouse press for several QGraphicsItem's in QT | I have a matrix of QGraphicsItem's in a QGraphicsScene and when I click an element it changes it's color. This is implemented with mousePressEvent(). I want to be able to click and hold and then move the cursor over other QGraphicsItem's and change their color too, hence trigger their mousePressEvent().
The problem is ... | I found a solution myself. I added all my QGraphicsRectItem's to a QGraphicsItemGroup and implemented the events for this group. In Group::MouseMoveEvent() I check the position of the cursor and apply the event to its children. It looks like this:
void Group::mouseMoveEvent ( QGraphicsSceneMouseEvent * event )
{
if... |
4,206,574 | 4,206,700 | Is ISO C++ code directly compilable in C++/CLI? | I want to write some library code to be shared across products and across platforms, including OS X and .Net.
My current research suggests that writing this core library code in C++ is a good approach. Obviously I could also use Java but it's not my strong suit - I'd rather stick with ObjC / C++ / C# where I can.
I bel... | In most cases, but not necessarily. For example, the STL/CLR is hideously slow in comparison to the BCL, and some things like nullptr refer to the managed nullptr, not the native nullptr. Even if your app compiled cleanly for .NET, that doesn't make it the right thing to do.
It would be much more reasonable to compile ... |
4,206,631 | 4,206,678 | C++ and iterator invalidation | So I'm going through Accelerated C++ and am somewhat unsure about iterator invalidation in C++. Maybe it's the fact that it is never explained how these iterators are constructed is the problem.
Here is one example:
Vector with {1,2,3}
If my iterator is on {2} and I call an erase on {2} my iterator is invalid. Why? In ... |
In my head, {3} is shifted down so the memory location of where {2} was so the iterator is still pointing to a valid element.
That may be the case. But it’s equally valid that the whole vector is relocated in memory, thus making all iterators point to now-defunct memory locations. C++ simply makes no guarantees eithe... |
4,206,660 | 4,206,873 | C++ -- Questions about function pointers | I have written the following code:
#include "stdafx.h"
#include <iostream>
using namespace std;
double funcA()
{
return 100.0;
}
int g(double (*pf)())
{
cout << (*pf)() << endl;
return 0;
}
int g2(double pf())
{
cout << pf() << endl;
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
g(&func... | C++ does, in fact, make a distinction between the types double() and double(*)(), but the difference is subtle. When you pass a function type as an argument to a function, the function-type automatically "degrades" to a function pointer. (This is similar, I suppose, to how an array type degrades to a pointer type whe... |
4,206,816 | 4,206,858 | ifstream: check if opened successfully | A colleague just told me that this code:
std::ifstream stream(filename.c_str());
if (!stream)
{
throw std::runtime_error("..");
}
would be wrong. He said ifstream evaluates to 0 if opening is successful. My code works, but I wanted to find the documentation but didn't see where it says how to check if opening was ... | operator! is overloaded for std::ifstream, so you can do this.
In my opinion, though, this is a horrible abuse of operator overloading (by the standards committee). It's much more explicit what you're checking if you just do if (stream.fail()).
|
4,206,922 | 4,207,072 | Formal Specification | Is there any library/tool for formal specification in C++, such as JML for Java, and Data Contracts in C#?
EDIT:
I am not looking for something more specific than, it's practical to use and adds some value/quality.
EDIT2:
I am not looking for UML tools, please see the examples I have provided.
| IBM Rational Rose UML software generates C++ code according to the complete UML model.
Never ever used it though, not really I mean. Just a brief look and only at UML functionalities.
|
4,207,034 | 4,207,064 | Why does the following code make my computer beep? | I'm having a really hard time understanding why is this piece of code making my computer beep. I've isolated this section of code to be the one producing the occasional beep, but I don't see what's the problem with it.
const int BUFFER_LENGTH = 8192;
char buffer [BUFFER_LENGTH + 1];
int recvResult;
do
{
recvResult... | The buffer probably contains a '\a' char which makes the computer beep. From 5.2.2 (Character display semantics) :
Alphabetic escape sequences representing nongraphic characters in the execution character set are intended to produce actions on display devices as follows:
\a (alert) Produces an audible or visible aler... |
4,207,106 | 4,207,210 | atomic append on a file descriptor, but at what offset? | in unistd.h
using open() with the O_APPEND flag gives atomic writes always to the end of the file...
this is great and all, but what if i need to know the offset at which it atomically appended to the file...?
i realize O_APPEND is often used for log files, but I'd actually like to know at what offset in the file it at... | To get the current position in a file descriptor, use lseek() with offset 0 and whence SEEK_CUR.
int fd = open(...);
if (fd) {
off_t positionWhereAppendingBegins = lseek(fd, 0, SEEK_CUR);
write(...);
close(fd);
}
Note that this will not give you reliable results if the descriptor was opened some other way,... |
4,207,134 | 4,207,223 | What is the proper declaration of main in C++? | Questions
What is the proper signature of the main function in C++?
What is the correct return type, and what does it mean to return a value from main?
What are the allowed parameter types, and what are their meanings?
Is this system-specific?
Have those rules changed over time?
What happens if I violate them?
| The main function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).
The name main is not reserved in C++ except as a function in the global namespace. Yo... |
4,207,346 | 4,207,363 | How can I traverse/iterate an STL map? | I want to traverse an STL map. I don't want to use its key. I don't care about the ordering, I just look for a way to access all elements it contains. How can I do this?
| Yes, you can traverse a Standard Library map. This is the basic method used to traverse a map, and serves as guidance to traverse any Standard Library collection:
C++03/C++11:
#include <cstdlib>
#include <map>
#include <string>
using namespace std;
int main()
{
typedef map<int,string> MyMap;
MyMap my_map;
... |
4,207,398 | 4,207,514 | getting a RGB value from a pixel and setting the rgb values back to the same pixel | In the code snippet below I am trying to retrieve the RGB values of a pixel in Visual C++ and then set the same RGB values back to be the same pixel. i.e. this is just a test. However when I do it the resulting image is similar but the colors are wrong/off. The resulting image appears to be totally missing the yellow c... | The way you are accessing the colour values is wrong. GetRValue and other functions are meant to operate on a COLORREF value which is laid out in memory as red-green-blue-reserved, whereas the format of an RGBQUAD is blue-green-red-reserved. By using the Get?Value macros on an RGBQUAD, you're swapping the red and blue ... |
4,207,466 | 4,207,496 | C++ Detect OS Version | I want to know how to detect the running OS using the C++ and which service pack installed
| For Windows, see this example called GetOSDisplayString from MSDN, in which the use of GetVersionEx is demonstrated.
|
4,207,506 | 4,207,559 | where is GL_MULTISAMPLE defined? | Although I have been discouraged from reading the OpenGL redbook, I am still doing it, because it is the only book designed for beginners, and tutorials and/or documentation don't quite substitute for a book although very important. So much for justifying myself :)
Now, there's an example for antialiasing using multisa... | GL_MULTISAMPLE is an used to be extension to OpenGL, until 1.3, and whether or not it is implemented depends on your hardware/drivers/vendor implementation. You might actually want to use GL_MULTISAMPLE_ARB instead. If you are on Windows, the platform provided OpenGL headers will not include this macro.
See also:
http... |
4,207,606 | 4,207,678 | Sub-Namespaces for Organization Bad Practice? | Would it be considered bad practice to use sub-namespaces for purely organizational purposes? For example:
namespace vehicles
{
namespace cars
{
// Stuff here
}
namespace boats
{
// More stuff here
}
}
I can see how this would be a problem on large projects, because it would b... | Why would it be less inconvenient to type vehicles::cars::function a lot in a small project?
Remember what purpose namespaces are supposed to serve. They are supposed to avoid name clashes, and not much else.
If you invent such a convoluted namespace structure that I'm tempted to just put a few using namespace ...'s at... |
4,207,696 | 4,207,782 | Split an Integer into its digits c++ | I'm trying to learn c++ on my own and I've hit a bit of a road block. The problem is I need to take an integer,split it into its digits and get the sum of the digits and display them.
Example:
input number: 123456
digits in the integer: 1 2 3 4 5 6
sum: 21
I have it all done, but when I rip the integer, into digits I ... | Your problem comes from the fact that you are reading the digits backwards, thus you need to print them out backwards. A stack will help you tremendously.
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stack>
int countDigitsInInteger(int n)
{
int count =0;
while(n>0)
... |
4,207,737 | 4,207,750 | How to convert std::string to const char*? |
Possible Duplicate:
Convert std::string to const char* or char*
void Foo::bar(const std::string& foobar) {
// ...
const char* foobar2 = (char*)foobar;
// ...
}
That does not work and I get an error during compilation about invalid casting.
Is there some other way to convert std::string to const char*?
| Use foobar.c_str().
You might find this link useful: http://www.cppreference.com/wiki/string/start
|
4,208,038 | 4,208,085 | Forward headers for STL containers | The header <iostream> has a companion <iosfwd> which is sufficient if I only need pointers or references to streams. The latter is a common scenario when overloading operator<<.
Is there such a header for the STL containers? I want to define a couple of functions that take references to STL containers, and I do not wan... | No, unfortunately not. The standard only introduced <iosfwd> for backward compatibility to support code that was written for the old, non-templated IO streams library.
|
4,208,223 | 4,208,335 | Detect the existence of types | SFINAE allows us to detect if a type has certain data members or member functions. Can it also be used to detect if a type exists at all? Background: I want to know whether <vector> was included or not.
| It can do, although I've only managed to make it work in C++0x.
struct no_type {};
struct is_vector_included {
template<typename U> static decltype(std::vector<U>::iterator()) func( U* );
template<typename U> static no_type func( ... );
static const bool value = !std::is_same<no_type, decltype(func<int>(nul... |
4,208,264 | 4,208,399 | Looking for a sample C++ program for learning how to start up a project | I've learned the most basic of C++ but I feel like I don't know how to organise the code and start up a C++ project. I've searched for guides about project/code organization without very much luck.
So I want to find a litle well-coded real program to see how is it organised, but I find nothing. Do anyone know a real we... | This is mostly dependent on a couple of things:
Supported platform(s): this will push or pull you toward different code structure if you abstract the different platforms differently.
Build system: stuff like CMake, qmake, autocr*p, Ant, Bjam, jam, etc...
IDE: this won't be a show-stopper, but still could decide number... |
4,208,559 | 4,209,424 | Calling a member function with member data by using for_each | Dear all, I would like to call a member function (that expects a reference) for each object of (let's say) a vector that is a member of the same class, as the following code shows:
#include <functional>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
struct Stuff {
double x;
};
... |
The function you want to call cannot be simply identified by f1 but should be referred to as &Test::f1 (as in : member function f1 of class Test)
Function f1 does not take a single argument : as any non-static member function it has an implicit this parameter of type Test * const
Finally, a standard bind won't be able... |
4,209,060 | 4,209,120 | Text layout engine API for C++ | I have a project where I need to take input text and render it to an image. The text needs to be wrapped, have margins, kerning, letter spacing, specific fonts, and so on. It seems like I could write most of this by hand, but it also seems like something that there should be pre-existing libraries for.
I've looked at w... | Subprocesses can be pretty awesome, but I guess you are looking for something like pango or the font rendering engine in Qt. It looks like you can achieve everything you need with QPainter::drawText(...). See also QFont.
It is worth noting that I have dragged in Qt specifically for font rendering before, without using ... |
4,209,151 | 4,227,314 | Compiler cannot deduce the specialised template in C++ | I have the following code in a class
struct ConstrType{};
struct ConstrType3{};
struct ConstrType2{};
struct ConstrType1{};
template<typename InType, typename OutType, typename ConstrType>
class getInterestRateIndex_impl{
public:
getInterestRateIndex_impl(){
std::cout << "Generic getInterestedR... | The problem is that the outer if statement cannot deduce the type of the "then" branch and return a compounded type of boost structs and therefore always choosing the full unspecialised template
|
4,209,326 | 4,209,583 | Named? parameters in templates, functions | Is there any update in the upcoming C++0x standard on named parameters in templates and/or functions? For example, I would like to be able to write the following:
having defined previously:
template<class T = int,class Policy_1, class Policy_2>
class X
{
};
then in main:
X<Policy_2: NoReturn> x;
this same with fun... | For functions you can use the Named Parameters Idiom (in both C++98 and C++0x).
See C++ FAQ item 10.20 What is the "Named Parameter Idiom"?.
For template arguments I think you can use the idea of wrapping, using "type carrier" types that by their type encode which template argument they are. It gets complex. You might ... |
4,209,433 | 4,209,525 | C++ integral constants + choice operator = problem! | I have recently discovered an annoying problem in some large program i am developing; i would like to understand how to fix it in a best way. I cut the code down to the following minimal example.
#include <iostream>
using std::cin;
using std::cout;
class MagicNumbers
{
public:
static const int BIG = 100;
static co... | In spite of the conventional advice, I have found that static const int ... invariably gives me more headaches than good old enum { BIG = 100, SMALL = 10 };. And with C++11 providing strongly-typed enums, I now have even less cause to use static const int ....
|
4,209,541 | 4,209,578 | what is the use of c++ non-type template values? | What is the use of c++ non-type template values? What can be done with this:
template <int I>
class MyClass
{
public:
MyClass();
.
. //Use I;
.
}
that can't be done with this:
class MyClass
{
int I;
public:
MyClass(int i) : I(i) {}
.
. //Use I
.
}
The template version seems to me t... | With template you can do this:
template <int I>
class MyClass
{
int array[I];
}
|
4,209,684 | 4,209,786 | MS Visual C++ runtime library - what for? | What's in MS Visual C++ runtime library? I mean, I googled it, and I always found things like help, app xxxx gives me MS Visual C++ runtime library error, with no explanation.
I thought that Windows C runtime libraries come with Windows? Not with VC++? Thanks.
EDIT:
First, thanks for answers. I thing now I have bad ide... | A brief answer would be that the MSVS C/C++ runtime implements functions like malloc/free, stdio, iostream and some c++-stuff like dynamic_cast and exception handling. These differs between versions of visual studio, so there are different runtimes for different versions.
Windows ship mostly with a C API (the Win32 API... |
4,209,697 | 4,210,156 | How to find a string in string and replace it? | I have a std::string A I need to find in it string B with content like bla-bla-bla and replace it with other string C like abcdefg and if B was not found just put C at the beginning of A.
How to do such thing?
| void replace_or_merge(std::string &a, const std::string &b, const std::string &c)
{
const std::string::size_type pos_b_in_a = a.find(b);
if(pos_b_in_a == std::string::npos) {
a.insert(0, c);
}
else {
a.replace(pos_b_in_a, b.length(), c);
}
}
|
4,209,941 | 4,210,165 | How to make C++ function return to its first line? | So I have a function inside a win32 C++ console application like:
void initFFmpeg(string url ,string container, int w, int h, int fps)
{// we want to return here
encoder.SetConstants(fps, videoWidth, videoHeight, audioSampleRate);
// ... more code...
if (encoder.InitUrl(container, url, outputUserName) ==... | It appears that what you're trying to do is to keep trying various formats until ffmpeg successully opens the url. This is probably what you want to do (and IMHO cleaner than using a goto).
void initFFmpeg(string url ,string container, int w, int h, int fps)
{
do {
encoder.SetConstants(fps, videoWidth, vid... |
4,210,157 | 4,210,336 | php vs C++/Java for intensive processing, memory difference? | I have a php curl script that uses 10 MB per running session.
I'd like to scale things and add more requests but the curl and processing must be taking up too much memory. (I want to add like a 100,000 sessions)
If I had a server side C++ routine would the memory difference be that much different? I don't want to re-wr... | PHP is getting better with performance all the time, but it is still a fairly heavy language. If you were to use C/C++, you would definutely see major performance increases. For anything under high load, you definutely need to move away from PHP to a more performance-oriented application.
That said, I do agree with Goz... |
4,210,457 | 4,210,485 | MATLAB code library for C++ | Are there any good sources containg C++ versions of MATLAB functions? I am only looking for some basic functions i.e. fzero.
| fzero is non trivial.
If your function is polynomial, try GSL http://www.gnu.org/software/gsl/
|
4,210,462 | 4,210,479 | How to create simple tcp_connect and tcp_write functions? | So I need2 functions: 1) tcp_connect that would try to connect to tcp adress (given string like tcp://123.123.123.123:33333/) capable of returning some bool if connection was sucsessfull and simple tcp_write function capable to write a buffer of given langth on to opened connection. So where to get how to do it with b... | boost::asio, and here is the code you need: http://www.boost.org/doc/libs/1_44_0/doc/html/boost_asio/examples.html
|
4,210,470 | 4,210,489 | Looping on C++ iterators starting with second (or nth) item | I am looking for a readable, elegant way to do the following in C++, here shown in Python:
for datum in data[1:]:
# do work.
The iterators on the data in question may not support random access iterators, so I can't just use:
for (mIter = data.begin() + 1; mIter != data.end(); mIter++)
The best I've come up with i... | You can use std::next(iter, n) for a linear-time advance. You can also use the standard std::advance algorithm, though it isn't as simple to use (it takes the iterator by a non-const reference and doesn't return it).
For example,
for (mIter = std::next(data.begin()); mIter != data.end(); ++mIter)
or,
mIter = data.begi... |
4,210,567 | 4,210,744 | C++, boost: which is fastest way to parse string like tcp://adr:port/ into address string and one int for port? | we have std::string A with tcp://adr:port/ How to parse it into address std::string and one int for port?
| void extract(std::string const& ip, std::string& address, std::string& service)
{
boost::regex e("tcp://(.+):(\\d+)/");
boost::smatch what;
if(boost::regex_match(ip, what, e, boost::match_extra))
{
boost::smatch::iterator it = what.begin();
++it; // skip the first entry..
address = *it;
... |
4,210,710 | 4,210,955 | Cast pointer to member function to normal pointer | Currently I have a class of this kind, shortened for simplicity:
class MyClass {
public:
MyClass();
void* someFunc(void* param);
}
Now I need to call a function of this kind (not member of any class and which I unfortunately cannot change) but which I need to call anyway:
void secondFunc(int a, in... | The difference between a C function and a C++ member function is that C function uses cdecl calling convention, while member functions uses thiscall calling convention (and you can't even take their address!).
As I understand, you actually want that secondFunc() to call the member function of a particular instance of c... |
4,210,828 | 4,211,151 | C++: Linking extern variables from within a namespace | I can't seem to reference an externally-defined variable from within a namespace using extern. It works from the global scope, but as soon as a namespace is thrown in there, it fails to link.
My constants file looks like:
StringConstants.cpp
#include "MyString.h"
MyString test1("string1");
MyString test2("string2... |
$7.3.1/2 - "Every name first declared
in a namespace is a member of that
namespace."
This means that the name 'test2' is part of the anonymous namespace and should be defined in that namespace if it is used.
It is not an issue with the anonymous namespace alone but for that matter any namespace.
|
4,211,043 | 4,211,061 | Write quotes to a text file using ofstream, c++ | I want to write out quotes to be in the file and I don't know how the syntax should look.
ofstream file("myfile.txt");
if ( file.is_open())
{
file << "\n";
file << ""type of file""<< "=" << '\n'; // obviously this is wrong
file << "name = \n";
}
I want the text file to look like so:... | Use \" instead of just ", i.e.:
file << "\n"; // note not "/n"
file << "\"type of file\"" << "=" << "\n";
file << "name = \n";
Of course the middle line could just be:
file << "\"type of file\"=\n";
|
4,211,168 | 4,230,643 | Using MSHTML how do you set the focus on an input field? | Using MSHTML I'd like to set the user focus on a text element, what I've been given and tried so far doesn't work.
CComPtr<IHTMLInputTextElement> field;
field->put_value( .. ); // I have the right element as I can set the text...
VARIANT vStatus;
vStatus.vt = VT_BOOL;
vStatus.boolVal = VARIANT_TRUE;
field->put_status... | CComQIPtr<IHTMLElement2 > element2(field);
if(element2!=NULL) element2->focus();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.