question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,099,075 | 3,099,233 | Bitwise setting in C++ | #define OUTGOING_MASK 0x0c
#define OUTGOING_DISABLED 0x04
#define OUTGOING_ENABLED 0x08
#define OUTGOING_AUTO 0x00
#define REFER_SUPPORTED 0x80
Assume support is some value of type int.
I have a getter function
int get()
{
if(OUTGOING_DISABLED == support & OUTGOING_MASK)
return 1;
else ... |
I have a statement such as a1 = b & a2; How to know the value of b using bitwise operators?
You can't recover value of b, unless a has ALL bits set. "&" is irreversible.
Explanation. & operation has following table:
a b result
1 & 1 = 1
0 & 1 = 0
1 & 0 = 0
0 & 0 = 0
which means, to recover b, you could try to us... |
3,099,082 | 3,099,279 | twofaced file problem | I'm reading in my program some files from system32 folder; and one of these files (C:\Windows\System32\gdi32.dll) demonstrates a very strange behavior. When I'm reading it from my program, it shows size of 310'784 bytes; and when I view it's size from Explorer, it shows size of 404'480 bytes.
How could that be?
| The most likely explanation is that your program is 32-bit and Explorer is 64-bit. When a 32-bit program opens files in C:\Windows\System32 (which contains 64-bit DLLs), it's actually redirected to C:\Windows\SysWOW64 (which contains 32-bit DLLs). The size difference you're seeing is the difference between the C:\Windo... |
3,099,135 | 3,099,139 | c++ type error message from compiler, what does it mean? | I'm using g++ on fedora linux 13.
I'm just practicing some exercises from my c++ textbook
and can't get this one program to compile. Here is the code:
double *MovieData::calcMed() {
double medianValue;
double *medValPtr = &medianValue;
*medValPtr = (sortArray[numStudents-1] / 2);
return ... | sortArray[numStudents - 1] is a pointer to int, which can't be on the left side of a division (when you remember pointers are addresses, this makes sense). If you post more of your code, we can help you correct it.
Perhaps you want something like:
int *MovieData::calcMed() {
return sortArray[(numStudents - 1) / ... |
3,099,229 | 3,099,295 | In SDL, does SDL_Quit() free every surface? | Basically, on surfaces that are going to exist right until the program terminates, do I need to run SDL_FreeSurface() for each of them, or would SDL_Quit() take care of all this for me?
I ask mainly because the pointers to a number of my surfaces are class members, and therefore I would need to keep track of each clas... | It's been a while since I used SDL, but I'm pretty sure SDL_Quit just cleans up the screen surface (the main screen buffer that you set up at the beginning). You have to free the other surfaces you create manually or you get leaks. Of course, since they're already class members, one way to do that easily would be to ... |
3,099,360 | 3,101,748 | Threading Model for a Game Engine | I'm interested in getting threading into the small engine I'm working on in my spare time, but I'm curious over what the best approuch is. I'm curious about the recommended way to sync the physics thread with the rest of the engine, similar to ThisGuy. I'm working with the Bullet Physics SDK, which already use the data... | The easiest and probably most used variant is to run physic, render, ai, ... threads in parallel and syncronise them after each of them has finished with a frame/timestep.
This is not the fastest solution, but the one with the fewest problems.
Writing back the data to the rendering thread while this is running, leads t... |
3,099,385 | 3,100,047 | Inheritance and storing static class information | I'm trying to set up some stuff with Lua, but the specifics of Lua aren't important for my question.
What I would like to be able to do is call a function, say OpenLib<T>(L), and have it get the table name for a particular class (as well as it's table) and register it with Lua. It essentially boils down to this:
templ... | Using
template<typename T>
class LuaInfo
{
static const char* myTableName;
static lua_reg* myTable;
};
should work OK.
Your problem is that you need to define your static variables.
A single source file containing a bunch of lines like this will solve it
luaL_reg* LuaInfo<ag::ui::Widget>::myTable = 0;
const char *... |
3,099,445 | 3,099,530 | Please help me understand this syntax (implementing static assert in C++) | This syntax was used as a part of an answer to this question:
template <bool>
struct static_assert;
template <>
struct static_assert<true> {}; // only true is defined
#define STATIC_ASSERT(x) static_assert<(x)>()
I do not understand that syntax. How does it work?
Suppose I do
STATIC_ASSERT(true);
it gets converted... | STATIC_ASSERT(true);
indeed means
static_assert<true>();
which evaluates to nothing. static_assert<true> is just an empty structure without any members. static_assert<true>() creates an object of that structure and does not store it anywhere.
This simply compiles and does nothing.
On the other hand
STATIC_ASSERT(fals... |
3,099,595 | 3,099,658 | problem with va_arg() | I want to wirte a function with variable arguments in this way:
static void configElement(U32 localFaultId,
char* name,
U32 report,
U32 localId,
U32 detectTime,
U32 ceaseTime,...)
{
U3... | It looks like the compiler does not know what U32 is. Did you include all necessary headers?
|
3,099,638 | 3,099,660 | The difference between unsigned long and UINT64 | What is the difference between unsigned long and UINT64?
I think they are the same, but I'm not sure.
The definition of UINT64 is :
typedef unsigned __int64 UINT64
(by using StdAfx.h)
| UINT64 is specific and declares your intent. You want a type that is an unsigned integer that is exactly 64 bits wide. That this may be equal to an unsigned long on some platforms is coincidence.
|
3,099,674 | 3,099,750 | Virtual function and Classes | I need some answers to basic questions. I'm lost again. :(
q1 - Is this statement valid:
Whenever we define the function to be pure virtual function,
this means that function has no body.
q2 - And what is the concept of Dynamic Binding? I mean if the Compiler optimizes the code using VTABLEs and VPTRs then how is it ... |
False. It just means any derived classes must implement said function. You can still provide a definition for the function, and it can be called by Base::Function().*
Virtual tables are a way of implementing virtual functions. (The standard doesn't mandate this is the method, though.) When making a polymorphic call, t... |
3,099,695 | 3,099,706 | C++ Typedefs and operator overloading | If you define a type like typedef int MY_INT; and go on to overload, say, the adition operator of MY_INT like
MY_INT operator+(MY_INT a, MY_INT b);
will
MY_INT a, b;
a + b;
be different from
int A, B;
A + B;
?
Sorry for any syntax errors. I'm not near a compiler and I want to ask this before I forget about it.
| No. A typedef is actually an alias for another type. The original and typedef-ed types are the same.
|
3,099,947 | 3,099,990 | Multimap containing pairs? | Is it possible for a multimap to contain within it pairs? IE, rather then being defined as multimap<char,int> for instance, it would be defined as multimap<pair, pair>?
How would this multimap then be sorted? Also, how would one access the individual contents of each pair?
| Is it possible for a multimap to contain within it pairs?
Yes its possible.
How would this multimap then be sorted?
By the key/first pair (ie, first by the first element of the first pair, then by the second element of the first pair).
Also, how would one access the individual contents of each pair?
multimap<pair <T1, ... |
3,100,095 | 3,100,159 | Festival C/C++ API compiling an example, linking libraries error | I am having problems with the festival C++ API (Windows XP).
After I make both festival and speech_tools succesfully (Cygwin), I have a file, called festival_example.cc, which contains:
#include <stdio.h>
#include <festival.h>
int main(int argc, char **argv)
{
EST_Wave wave;
int heap_size = 210000; // default... | Replace -lib* with -l*.
For instance -libFestival won't work. Do
g++ festival_example.cc -I./festival/src/include -I./speech_tools/include -L./festival/src/lib -lFestival
|
3,100,121 | 3,100,288 | c++ Compression library - Deflate or Gzip | I'm looking for a useful compression library for c++ (on windows)
I need preferably Deflate or Gzip, and i need it to be compatible with .NET's System.IO.Compression.
Also if it will give me a decorator over a stream that would be great so i could do:
std::ostringstream stringStream;
CompressionStream cs(stringStream);... | Take a look on Boost.Iostream that provides such filter allowing to compress std::iostream
to gzip or zlib formats (they acutally use zlib under the hood but have nicer interface).
These formats are standard so anybody (.Net too) should open them,
|
3,100,311 | 3,100,438 | Emitting native code (for a specific platform) | How do you get started generating native code for a target platform? I've got (some) experience and (some) skill in C++, and am interested in going and writing my own compiler (for C++). But I've got little idea how I'm going to turn the end result into native code to execute on my target platform, which at the moment ... | Look at some of the other questions on writing compilers, such as learning-to-write-a-compiler, and having worked through something like the dragon book or Programming Language Pragmatics, you'll understand enough of LLVM or gnu lightning to use them as your back end.
Don't try to write a C++ compiler unless you have ... |
3,100,322 | 3,125,903 | boost.test vs. CppUnit | I've been using CppUnit for quite a while now (and am happy with it). As we are using more and more parts of the boost library I had a short look on boost.test and I'm wondering now if I should switch to boost.test in a new project or not.
Can anyone here tell me about the differences between the two frameworks and the... | Do yourself a favor and go straight to Google Test, which makes CppUnit and boost::unit_test look clunky and repetitive.
For example, say you have a simple fixture:
class MyFixture : public ::testing::Test
{
protected:
int foo;
virtual void SetUp() { foo = 0; }
};
To add a test to your fixture, write it!
TEST_F... |
3,100,341 | 3,106,081 | Boost-Python raw pointers constructors | I am trying to expose a C++ library to python using boost-python. The library actually wraps an underlying C api, so uses raw pointers a lot.
// implementation of function that creates a Request object
inline Request Service::createRequest(const char* operation) const
{
blpapi_Request_t *request;
ExceptionUtil... | Your class_<blpapi_Request_t>; does not declare anything; is that code the correct version?
If so, then update it:
class_<blpapi_Request_t>("blpapi_Request_t");
That said, what that error indicates is that you are trying to use the Request object with an automatic conversion to a python object which has not been defin... |
3,100,343 | 3,100,775 | Connecting to oracle database using C++, the basics | i have a question about the theory here, i'm just starting a project which is based on C++ applications integrating with oracle DB's, i've came to two choices, OCCI, and OCI
the OCCI is said to be aimed at C++ environment, but i was wondering, if it would be any good to use the OCI libraries from my C++ app since it is... | You can have a look at OTL it's a wrapper above the OCI or OCCI (not sure) will give some templates and samples to start with oracle connection in c++.
|
3,100,365 | 3,100,936 | Why is −1 > sizeof(int)? | Consider the following code:
template<bool> class StaticAssert;
template<> class StaticAssert<true> {};
StaticAssert< (-1 < sizeof(int)) > xyz1; // Compile error
StaticAssert< (-1 > sizeof(int)) > xyz2; // OK
Why is -1 > sizeof(int) true?
Is it true that -1 is promoted to unsigned(-1) and then unsigned(-1) > sizeof(i... | The following is how standard (ISO 14882) explains abort -1 > sizeof(int)
Relational operator `>' is defined in 5.9 (expr.rel/2)
The usual arithmetic conversions are
performed on operands of arithmetic or
enumeration type. ...
The usual arithmetic conversions is defined in 5 (expr/9)
... The pattern is called the... |
3,100,499 | 3,100,836 | Signal a thread accross Process boundary | Would it be possible for a COM client to signal a thread in a COM Server?
| To let a COM client signal the server, you'd need some COM interface like this:
interface IClientServerSignalling
{
void SignalMyServer();
}
The COM Client would QueryInterface on some existing object (or you could implement a specific object just for this purpose) and then call the method, which gets marshalled ac... |
3,100,554 | 3,100,786 | Wrapping C++ dynamic array with Python+ctypes, segfault | I wanted to wrap a small C++ code allocating an array with ctypes and there is something wrong with storing the address in a c_void_p object.
(Note: the pointers are intentionally cast to void*, 'cause later I want to do the allocation the same way for arrays of C++ objects, too.)
The C(++) functions to be wrapped:
voi... | From just looking at it, it seems that the problem is not in the small/big array allocation, but in a mix of 32bit and 64bit addresses.
In your example, the address of the small array fits in 32 bits, but the address of the big array doesn't.
|
3,100,714 | 3,101,090 | GetDIBits() is failing with PNG compression | I am trying to get the size of PNG image (Without storing into file). I am using this code as reference. When calling GetDIBits(), size of image would get updated into bi.biSizeImage. Everything works fine when bi.biCompression is BI_RGB. Then I have changed the compression mode from BI_RGB to BI_PNG; GetDIBits() start... | According to http://msdn.microsoft.com/en-us/library/dd145023%28VS.85%29.aspx:
"This extension is not intended as a means to supply general JPEG and PNG decompression to applications, but rather to allow applications to send JPEG- and PNG-compressed images directly to printers having hardware support for JPEG and PNG ... |
3,100,842 | 3,100,893 | C++ dynamic review tools | What's the best tool (commercial/open source) you've used for dynamic review/memory analysis of a C++ application?
EDIT: removed 'static' as there is already a great question on this topic (thanks Iulian!)
| For dynamic memory analysis definitely Valgrind.
|
3,100,989 | 3,101,403 | Problem in Communicating with Digitally SIgned c# com dll from c++ in WIN 7 ultimate | I have a c# com dll which I register to registry Using regasm . I communicate with this c# dll from a c++ exe . I use create instance to initialize the dll . when both these components are not signed digital it is working perfectly . when they are digitally signed cocreate instance fails. get last error says "Token ... | Do you re-register your DLLs using regasm once you sign them?
Use regedit to check the registration info at HKEY_CLASSES_ROOT\CLSID\{your-guid-here}\InProceServer32, eg:
Assembly REG_SZ YourComObjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=abcdfc550b465bd3
If your PublicKeyToken=null then this is the ... |
3,100,997 | 3,101,049 | C++ - STL vector question | Is there any way to make std::vector faster on reserving + resizing?
I would like to achieve the performance which would be somewhat equivalent to plain C arrays.
See the following code snippets:
TEST(test, vector1) {
for (int i = 0; i < 50; ++i) {
std::vector<int> a;
a.reserve(10000000);
a.resize(... | Well naturally the first 2 tests are slower. They explicitly go through the entire vector and call "int()" on each element. Edit: This has the effect of setting all the elements to "0".
Just try reserving.
There is some very relevant info to your question in this question i asked a while back:
std::vector reserve() a... |
3,101,160 | 3,116,336 | ide code information | I've been annoyed lately by the fact that PyDev doesn't information about classes and function when it code completes wxPython code.
Can anybody tell me FOSS IDE's or extensions that offer code information (function params, returns etc.) when it code completes for C/C++ and Python.
I am a fan of CodeLite, Eclipse CDT a... | Vim + Exuberant Ctags
See here, here and here for C++ autocompletion (also referred to as IntelliSense, taken from the name for Visual Studio's autocomplete).
And here for Python autocomplete/"intellisense" for vim. (I should point out I found the link to that from this post on SO).
If that doesn't include the ctags fo... |
3,101,185 | 3,101,207 | Why C++ STL does not provide hashtable and union data structures? | At various places, I've read that STL does not provide hashtable and union data structures. How could these be implemented using other existing STL data structures?
| Try the std::tr1::unordered_map for your hash map. std::map is ordered, so it's not really as efficient as hash. Not sure what you mean by a union data structure, but you can have unioned structs in C++
EDIT: Additionally there are many other implementations of hash maps that some have done. Boost has an unordered m... |
3,101,211 | 3,101,232 | c++: explain this function declaration | class PageNavigator {
public:
// Opens a URL with the given disposition. The transition specifies how this
// navigation should be recorded in the history system (for example, typed).
virtual void OpenURL(const GURL& url, const GURL& referrer,
WindowOpenDisposition disposition,
... | '= 0' means it's a pure virtual method. It must be overriden in inheriting class.
If a class has a pure virtual method it is considered abstract. Instances (objects) of abstract classes cannot be created. They are intended to be used as base classes only.
Curious detail: '= 0' doesn't mean method has no definition (no ... |
3,101,225 | 3,119,212 | Problems calling Python from C++ | test.py
def add(a,b):
""" """
print a,b,a+b
return a+b
c program
#include <python.h>
int _tmain(int argc, _TCHAR* argv[])
{
try
{
PyObject *pName,*pModule,*pDict,*pFunc,*pArgs1,*pArgs2,*pOutput;
Py_Initialize();
if(!Py_IsInitialized())
return -1;
pModule=PyImport_ImportModule("test");
pDict=PyModu... | I found it contains some chinese words in first line.
#XXX
And, it also didn't work in pythonwin.
Said something wrong.
So, I deleted them, and it's OK!
|
3,101,387 | 3,101,425 | Setting processor affinity for a process and its Effects | I am having an application which has a UI module and other supporting services. These other services have memory leaks and other thread synchronization issues. Hence in some machines especially quad core, dual core machines the services crash every now and then.
I know the best way to fix this is to clean up the memory... | This certainly depends on whether those services rely on threading. If they are single-threaded you won't notice much difference.
In your case since services are multithreaded they might or might not experience perfomance penalty - this will depend on actual design, specifically on whether they rely on several threads ... |
3,101,487 | 3,107,571 | Release mode static library much larger than debug mode version | today i found out that the compiled static library i'm working on is much larger in Release mode than in Debug. I found it very surprising, since most of the time the exact opposite happens (as far as i can tell).
The size in debug mode is slightly over 3 MB (its a fairly large project), but in release it goes up to 6,... | The difference is specifically because of link-time code generation. Read the chapter Link-Time Code Generation in Compilers - What Every Programmer Should Know About Compiler Optimizations on MSDN - it basically says that with LTCG turned on the compiler produces much more data that is packed into the static library s... |
3,101,771 | 3,103,660 | ESP error when sending window messages between threads | I have an Observer class and a Subscriber class.
For testing purposes, the observer creates a thread that generates fake messages and calls CServerCommandObserver::NotifySubscribers(), which looks like this:
void CServerCommandObserver::NotifySubscribers(const Command cmd, void const * const pData)
{
// Executed in... | I eventually decided to do it without window messages and am now posting my workaround here. Maybe it will help someone else.
Instead of letting the observer post window messages to its subscribers, I let the observer put data into synchronized subscriber buffers. The dialog class subscriber uses a timer to periodicall... |
3,101,811 | 3,101,898 | how to configure dynamic linking of libxml2? | I don't want to look stupid, but how should I link libxml2 to my g++ project (Linux environment)? What should I add to my code besides #include <libxml/tree.h>? Thanks for a link or a quick hint!
ps. I added this to my CXXFLAGS: xml2-config —cflags --libs. Enough?
| CXXFLAGS are for the compiler, LDFLAGS for the linker.
So add
xml2-config --libs
to your LDFLAGS
and
xml2-config --cflags
to your CXXFLAGS
|
3,101,906 | 3,102,168 | Two-way inclusion of classes & template instances | I'm having a problem when trying to compile these two classes (Army and General) in their own header files:
#ifndef ARMY_H
#define ARMY_H
#include "definitions.h"
#include "UnitBase.h"
#include "UnitList.h"
#include "General.h"
class Army
{
public:
Army(UnitList& list);
~Army(void);
UnitBase& oper... | I can't tell what Army.h line 21 is because the one you posted doesn't have that many lines. The only thing I can see that's not declared in that header is UnitList. Is it properly forward-declared or have a header include you aren't showing us?
Do generalbase.h or Warrior.h include Army.h? If so, that would cause the ... |
3,102,008 | 3,102,061 | Choose a number from an array | Is there any function or method to randomly choose a number (or 2 numbers or more) from an array?
| Depending on how many numbers you need, the size of the array, and whether the array needs to retain its order, you could use std::random_shuffle to reorder the array and then just loop from 0..n-1 to get n random numbers. This works better when you want to get a lot of numbers relative to the length of the array.
If t... |
3,102,058 | 3,110,475 | Is MsiOpenProduct the correct way to read properties from an installed product? | Given an MSI product code I want to get the upgrade code (among other properties) from an already installed product. I have tried this by calling the MsiOpenProduct method, followed by MsiGetProductProperty(). An (abbreviated) example looks like this:
MSIHANDLE handle = NULL;
MsiOpenProduct(strProductCode,&handle);
CSt... | MsiOpenProduct should be fine So long as you don't run any sequences or actions, it won't do anything. If you want to silence the dialog, you can with careful use of either MsiSetInternalUI() or MsiSetExternalUI().
Another approach you can take, as long as the ProductCode and UpgradeCode are safely static (i.e. as long... |
3,102,096 | 3,102,134 | When do C++ POD types get zero-initialized? | Coming from a C background, I've always assumed the POD types (eg ints) were never automatically zero-initialized in C++, but it seems this was plain wrong!
My understanding is that only 'naked' non-static POD values don't get zero-filled, as shown in the code snippet. Have I got it right, and are there any other impor... | Assuming you haven't modified a before calling test(), a has a value of zero, because objects with static storage duration are zero-initialized when the program starts.
d[0] has a value of zero, because the constructor invoked by std::vector<int> d(1) has a second parameter that takes a default argument; that second ar... |
3,102,485 | 3,102,541 | How to select groups of numbers with the same sum from an array | I have an array from ten (or more) numbers, for example:
arr[1,2,3,4,5,6,7,8,9,10]
I want a method to check if three numbers from this arrays have the same sum to another three numbers (I want to get all the possibilities!), for example:
{1.8.10} {2.10.7} {3.7.9} {4.9.6} {5.6.8} {Sum of each set: 19}
{1.6.10}... | Create a map of sets. Setup a triple nested for loop and start adding numbers. Every sum becomes a key into the map. The set is the 3 numbers you used. Should only be a dozen or so lines of code.
map<int,set<int> > sums;
for(int i=0; i<ARRAY_SIZE; i++)
{
for(int j=0; j<ARRAY_SIZE; j++)
{
if(j <=... |
3,102,580 | 3,102,598 | Using a class type as map key_value | Could a variable of Data be used as a map key?
struct Data {
Data(int X, int Y) {x=X; y=Y;}
int x; int y;
}
int main()
{
std::map<Data, int> map_;
map_.insert(std::make_pair(Data(1,2), 0)); //error inserting
}
| Yes, but you either need to define operator< for the class type or use a custom comparison function for the std::map.
There is an example of using a custom comparison function in the STL documentation.
|
3,102,805 | 3,102,829 | What does boost::thread do if it fails to create the thread? | What does boost::thread do if it fails to create the thread?
The winAPI returns a NULL (I guess posix does something similar) but as thread is an object how do I test to see if the thread was created?
| According to the API, it throws a boost::thread_resource_error if the thread creation fails.
I guess you cannot create an invalid boost::thread object: if something goes wrong, the constructor throws thus preventing the object creation.
|
3,102,888 | 3,102,930 | Game Development: How to limit FPS? | I'm writing a game, and I saw the FPS algorithm doesn't work correctly (when he have to calculate more, he sleeps longer...) So, the question is very simple: how to calculate the sleeptime for having correct FPS?
I know how long it took to update the game one frame in microseconds and of course the FPS I want to reach.... | The number of microseconds per frame is 1000000 / frames_per_second. If you know that you've spent elapsed_microseconds calculating, then the time that you need to sleep is:
(1000000 / frames_per_second) - elapsed_microseconds
|
3,102,937 | 3,102,995 | C++: why is the program reading the last blank from an input file as an element | My input file is:
2 5 <-- extra space at the end
4 <--extra space at the end
int main(){
ifstream input("input.txt");
istream& in = input;
string line1;
while( getline(in,line1)){
istringstream number1(line1);
while(number1.good()){
number1 >> temp1;
cout<<temp... | The problem is with the while (number1.good()) loop. The number1 fail state will not be set until after the number1 >> temp1 extraction fails, but you don't test the fail state until the next time the loop condition is tested, which is after you print out the result of that extraction. You should change the inner loo... |
3,102,991 | 3,103,078 | Menu disappears after running program later | Okay, so at first when i run my win32 program the menu works fine, however when i open the application later the next day or such the menu is gone but the code never changed. im making the menu with a .rc file. is this the recommended way?
resource.rc
#include "resource.h"
IDR_MYMENU MENU
BEGIN
POPUP "&File"
... | The content of your RC file looks fine, so I don't think the problem is there. I doubt the problem is in Bloodshed either -- while I'm not particularly fond of Dev-C++, I doubt it's causing anything like this. That leaves your code for the application as the most likely culprit for causing the problem. Unfortunately, y... |
3,103,007 | 3,103,049 | How to convert char* to unsigned short in C++ | I have a char* name which is a string representation of the short I want, such as "15" and need to output this as unsigned short unitId to a binary file. This cast must also be cross-platform compatible.
Is this the correct cast: unitId = unsigned short(temp);
Please note that I am at an beginner level in understandi... | I assume that your char* name contains a string representation of the short that you want, i.e. "15".
Do not cast a char* directly to a non-pointer type. Casts in C don't actually change the data at all (with a few exceptions)--they just inform the compiler that you want to treat one type into another type. If you cast... |
3,103,153 | 3,103,314 | Overloaded virtual function call resolution | Please consider the following code:
class Abase{};
class A1:public Abase{};
class A2:public A1{};
//etc
class Bbase{
public:
virtual void f(Abase* a);
virtual void f(A1* a);
virtual void f(A2* a);
};
class B1:public Bbase{
public:
void f(A1* a);
};
class B2:public Bbase{
pub... | The choice of which version of f to call is made by looking at the compile-time type of the parameter. The run-time type isn't considered for this name resolution. Since b1 is of type Bbase*, all of Bbase's members are considered; the one that takes an A2* is the best match, so that's the one that gets called.
|
3,103,164 | 3,103,194 | Return dynamic array in C++ | I need to return a unsigned int* from a function. The code below will compile but will crash at run time on a Windows 64 bit machine. I know I am making a silly mistake somewhere and can someone point it out for me. :p. I also have declared the function in my header, so I know its not that error.
Please note I have cen... | Well, for starters you have output[1] and output[2]. Arrays are zero-indexed in c/c++, so these should be: output[0] and output[1].
But, since you're asking about c++... I urge you to use std::vector or std::pair.
(Of course, for readability's sake, you might just want to use a trivial struct with useful field names)... |
3,103,445 | 3,103,483 | How do I use C functions that have "this" arguments in a C++ program? | I want to copy and paste a C function I found in another program into my C++ program.
One of the function arguments uses the "this" pointer.
void cfunction( FILE *outfilefd, const VARTYPEDEFINED this);
The C++ compiler errors here on the function prototype:
error C2143: syntax error : missing ')' before 'this'
How... | You have two choices. You can leave the code as C, and just create a C++ header to let you call that C code from C++:
#ifdef __cplusplus
extern "C" {
#endif
void cfunction(FILE *, const VAR);
#ifdef __cplusplus
}
#endif
Or you can rewrite that function enough to get it to compile as C++ (probably just rename it... |
3,103,560 | 3,231,839 | Convert C++ Code to Assembly for SPIM | I'm having a lot of trouble getting my compiled assembly file working on SPIM. Basically I want to write a c++ file, and then generate a .s file that I can open in SPIM without error. This means that the assembly must be in MIPS32 ABI using MIPS I instructions (some MIPS II). How do I do this? Right now I'm using g... | Give the compiler -S option, it will generate the assembly code. Then you will have to edit the code so that SPIM accepts it.
You'll also want g++ -S -fno-delayed-branch if you enable optimization like -O1 or -Og for more readable code. Usually SPIM is configured to simulate a MIPS without branch-delay slots, but gc... |
3,103,568 | 3,103,586 | How to write portable code in c++? | What are the things that I should keep in mind to write portable code? Since I'm a c++ beginner, I want to practice it since beginning.
Thanks.
|
learn to use the standard library
read books (eg. this one)
when you're experienced, learn to use boost
|
3,103,691 | 3,103,701 | Hot-pluggable C++ library possible? | I'm looking to "hot plug" a library of C++ code. I'm interested in having this technique work cross platform between Linux/Mac/Windows. Basically I want to have the main program #include "StateMachine.h" which defines all callable interfaces. Then at runtime and DURING EXECUTION load and unload StateMachineLibrary.a... | Define a base interface and derive your implementations from it. Put these into dynamic libraries (DLL/SO) and load them at runtime. The library will just need a static factory function to deliver an instance of its implementation to you.
// shared
class Base {
public:
virtual void DoTheWork() = 0;
};
// within th... |
3,103,934 | 3,104,006 | issues with C++ executable | I have a C++ generated executable in Solaris 8. The problem I have is that this executable uses a command line parameter to run.
For example:
$ myprog 123412341234AB
This is a valid 14 digit hexdecimal value. However, if for some reason there are symbols like ^ > < >> << & etc., then the program does not behave pro... | You can't fix this by modifying your program -- those special characters are being
interpreted by the shell before your code ever sees them.
You can prevent this by single-quoting the command-line argument:
myprog 'some_string_<with_special&>!chars'
or by escaping the special characters (by preceding each one with a ... |
3,103,938 | 3,104,078 | p/invoke a 32-bit dll from a C# program running on an x64 machine | I have a C# program that I compile with all of the default settings on an x64 computer.
I want to p/invoke a DLL which I know is a 32-bit (unmanaged) C++ DLL.
I can get this to work when my C# program runs on a 32-bit machine, but not a 64-bit machine.
How can I specify in the DllImport call that I am calling into a 3... | Running 32-bit unmanaged code in a 64-bit process is not possible. Or the reverse. The options you have available:
Force the EXE to run in x86 mode with the Target Platform setting in the Build tab
Recompile the C++ DLL in x64 mode. That's often possible without too many hassles, provided you have the source code a... |
3,103,968 | 3,104,119 | #include being ignored | So,
I've got this code I'm trying to update. It was written for visual studio 6, and I'm trying to get it to compile in visual studio 2010.
In stdafx.h, it includes afx.h and afxwin.h and a few other things necessary for the program to work. Notably, there's usage of CString in other header files.
At the top of the in... | Passing my comment to an answer.
CString in VS 6 times was a class and it changed afterwards to be a template. Maybe it has something to due with that?
The problem had to do with using
typedef with CString. Post VS 6,
that's not possible. I just changed
references by hand, and it compiles
now.
|
3,104,282 | 3,104,322 | Question About Which Design Pattern To Use | Given two classes:
First class performs AES encryption / decryption and returns encrypted / decrypted data given a certain key and chain.
Second class gathers data to be encrypted and then passes it to the encryption / decryption class.
Is it proper design to call directly the encryption class from the class that gathe... | Personally, I would create some kind of abstract interface representing an encryption algorithm, with a factory function taking the key and producing a concrete instance of an encryption algorithm with a key installed. So the 'second class' here would call directly to the 'first class', but there would be a 'third clas... |
3,104,356 | 3,106,427 | In Visual Studio 2010 why is the .NETFramework,Version=v4.0.AssemblyAttributes.cpp file created, and can I disable this? | I've recently upgraded to Visual Studio 2010. Now when I build projects I get a line that reads:
1> .NETFramework,Version=v4.0.AssemblyAttributes.cpp
I've learned that this is the result of the new build engine, msbuild.exe, but this file is actually auto-created and placed in my local temp directory (c:\Documents an... | This is common to all languages (C#, VB, and F# have something similar too).
One way you can disable it is to override the GenerateTargetFrameworkMonikerAttribute target thusly:
<!-- somewhere after the Import of Microsoft.somelanguage.targets -->
<Target Name="GenerateTargetFrameworkMonikerAttribute" />
in your proje... |
3,104,389 | 3,175,564 | Can I bind an existing method to a LLVM Function* and use it from JIT-compiled code? | I'm toying around with the LLVM C++ API. I'd like to JIT compile code and run it.
However, I need to call a C++ method from said JIT-compiled code. Normally, LLVM treats method calls as function calls with the object pointer passed as the first argument, so calling shouldn't be a problem. The real problem is to get tha... | The dudes from the LLVM mailing list were helpful enough to provide a better solution. They didn't say how to get the pointer from the method to the function, but I've already figured out this part so it's okay.
EDIT A clean way to do this is simply to wrap your method into a function:
int Foo_Bar(Foo* foo)
{
retur... |
3,104,467 | 3,105,071 | Type conditionals in C++ templates? | I have a method in C# as follows (which wraps a number across a range, say 0 to 360... if you pass 0-359 you get the same value, if you pass 360 you get 0, 361 gets 1, etc.):
/// <summary>
/// Wraps the value across the specified boundary range.
///
/// If the value is in the range <paramref name="min"... | With the facilities provided by numeric_limits, you don't really need to use any complex specializations or anything like that for the infinity check.
template <typename T>
const T& MathHelper::wrap(const T &value, const T &min, const T &max) {
bool isInfinity = std::numeric_limits<T>::has_infinity()
... |
3,104,509 | 3,104,797 | Getting input if the window is not active (Windows) | Short version:
How can I receive input messages in Windows with C++/C when the window is not active?
Background information:
I'm currently working on an Input System that should not depend on any window, so it can e.g. be used in the console as well.
My idea is to create an invisible window only receiving messages, whi... | Options:
RegisterHotKey if you need to register just one or a few hotkeys
SetWindowsHookEx with WH_KEYBOARD / WH_KEYBOARD_LL. Use when you need to filter many or all keyboard events. However, the hook code needs to be implemented in a DLL (which is loaded into other processes). You need separate 32 bit and 64 bit vers... |
3,104,543 | 3,104,591 | C++ allocator<X>::deallocate(NULL,1) allowed? | Both free(NULL) and ::operator delete(NULL) are allowed. Does the allocator concept (e.g. std::allocator also allow deallocate(NULL,1), or is it required to put your own guard around it?
| You'll need to add your own check.
According to §20.4.1.1/8, deallocate requires:
p shall be a pointer value obtained from allocate(). n shall equal the value passed as the
first argument to the invocation of allocate which returned p.
allocate throws an exception when storage can't be given (§20.4.1.1/7). In oth... |
3,104,554 | 3,104,643 | inline functions in c++ | here is a small question about inline functions in c++.
At what stage of the compilation in C++ are the inline functions actually inlined at the call?
how does that basically work.
lets say if the compiler has decided that a particualr function has to be inline after the programmer has requested with an inline keyword ... | It will vary by compiler. And some stages in some compilers will have no corresponding stages in other compilers. So your question doesn't really have a definite answer.
But generally it's done after the parse tree for the function is created, but before code is actually generated or many optimizations are done. Thi... |
3,104,772 | 3,104,827 | Should I use the C or C++ implementation for returning a maximum size of a variable type? | From a standards standpoint, should I use the following from the C++ <limits> header?
UCHAR_MAX which is the c implementation or
std::numeric_limits<unsigned char>::max() which is the C++ implementation.
The result is equivalent between the two versions but should I choose an implementation based on some standard or on... | If you want the code to be able to compile as C, then you pretty much need to use <limits.h>. If you're writing C++, it's probably better to use the C++ <limits> header instead. The latter lets you write code that will work in templates that can't really be duplicated with the C header:
template <class T>
class mytempl... |
3,104,838 | 3,105,167 | How to detect client connection to a named pipe server using overlapped I/O? | I was studying the MSDN examples of using named pipes:
Named pipe server using overlapped I/O
Named pipe client
The server easily detects when the client is disconnected and creates a instance of a named pipe. But I cannot figure out how the server knows that a client is connected to a pipe before any data from clien... | Not sure I understand the hang-up. The server calls ConnectNamedPipe to wait for a client connection. No data needs to be sent. Nor can it be sent, you cannot issue a ReadFile until a client is connected. Note that the SDK sample uses this as well.
If the server disconnects ungracefully (without notifying the clien... |
3,104,926 | 3,106,234 | change value inside multimap | I have a
multimap<key1,pair<key2, value2>>
I want to change value2 in this multimap.
typedef std::pair<int, int> comp_buf_pair; //pair<comp_t, dij>
typedef std::pair<int, comp_buf_pair> node_buf_pair;
typedef std::multimap<int, comp_buf_pair> buf_map; //key=PE, value = pair<comp_t, dij>
typedef buf_map::iterator It_... | The statement it->second.second = updated_dij; will overwrite the old value. Since you don't change the key field or indicate what a new key would be, this seems sufficient.
Is this what you are looking for or do you want to insert updated_dij under a new key and delete the old key?
|
3,104,993 | 3,105,028 | How to hide a function based on a template parameter | I'm using Visual Studio 2008. I have this class:
template <bool T1>
class Foo {
public:
void doSomething() {}
Foo<T1>& operator=(int a) {
doSomething();
return *this;
}
};
But I want that the method operator= be hidden (by simply doing: return *this) if the template parameter T1 is false.
... | You can statically assert the condition:
Foo<T1>& operator=(int a) {
BOOST_STATIC_ASSERT(T1);
doSomething();
return *this;
}
|
3,105,001 | 3,105,769 | Why is there no reallocation functionality in C++ allocators? | In C the standard memory handling functions are malloc(), realloc() and free(). However, C++ stdlib allocators only parallel two of them: there is no reallocation function. Of course, it would not be possible to do exactly the same as realloc(), because simply copying memory is not appropriate for non-aggregate types... | From:
http://www.sgi.com/tech/stl/alloc.html
This is probably the most questionable
design decision. It would have
probably been a bit more useful to
provide a version of reallocate that
either changed the size of the
existing object without copying or
returned NULL. This would have made it
directly useful for objects... |
3,105,105 | 3,105,216 | What is the most appropriate way to initialize a bi-dimensional array of objects? | I need a dynamically allocated bi-dimensional array of objects.
I declared a static pointer to pointer to object as follows:
server_session **server_session::Pglvcl_sess;
There's a method to populate dynamically the array of array of object:
int server_session::createSession()
{
int ret = -1;
// looks for the next... | Any reason not to use
Vector<Vector<server_session> >
and let it do the dynamic allocation and management for you?
|
3,105,114 | 3,105,382 | How to get printf style compile-time warnings or errors | I would like to write a routine like printf, not functionally-wise, but rather I'd like the routine to have the same time compile check characteristics as printf.
For example if i have:
{
int i;
std::string s;
printf("%d %d",i);
printf("%d",s.c_str());
}
The compiler complains like so:
1 cc1plus: warnings ... | Different compilers might implement this functionality differently. In GCC it is implemented through __attribute__ specifier with format attribute (read about it here). The reason why the compiler performs the checking is just that in the standard header files supplied with GCC the printf function is declared with __at... |
3,105,265 | 3,105,456 | Subtle syntax error in default parameter not caught by compiler | I started getting the error, "error C2059: syntax error : 'default argument'" for a line of code that declared a function with a string argument that was given a default parameter. This was obviously a bit frustrating, as the error message was not exactly enlightening (I know it's a 'default argument'!), and the exact... | Agreed with @tlayton. Having dabbled a bit in parsers myself, I can attest that generating good error messages for syntax errors that confuse the parser's sense of scope can be very hard to do.
This particular case is however close to a defect. The irony is that in VS2010, the compiler still generates the same lousy ... |
3,105,381 | 3,105,548 | how to call C++ dll function with int& and int* parameters from C#? | My C++ DLL have a function like this:
void func1(int& count, int* pValue);
this function will determine the "count", and put some values into the pValue int array which is the length of "count".
how can I define my C# code? you can ignor the [DllImport ...] part.
thanks,
| By ref & isn't going to happen as far as I've worked out.
MSDN has the answers you seek
and don't forget to export your function from C++ as extern "C"
According to MSDN: Default marshaling for arrays on the C# side I think you want something like the following
public static extern void func1(
out int count,
[Mar... |
3,105,476 | 3,105,477 | In C++, does adding a friend to a class change its memory layout? | Also, does it matter where in the class you declare the friend ?
Does it matter if you add a friend class or a friend function ?
| No it doesn't. It's a purely compile-time thing: similar to access modifiers themselves.
Despite the fact that you write the declaration inside the class, you don't really add a friend to a class. You'd basically declare something else as a friend of the class and simply allow it to access the class's private members, ... |
3,105,739 | 3,105,902 | Is there a way to Boost.Assign a ptr_vector? | Usually like this:
#include <boost/assign/std/vector.hpp>
vector<int> v;
v += 1,2,3,4,5;
Except for a:
#include <boost/ptr_container/ptr_vector.hpp>
boost::ptr_vector<int> v;
If you need to know the reason; I'm using ptr_vector instead of vector only so I don't have to delete elements, but I need to initialize it usi... | Use Boost.Assigns ptr_list_of():
#include <boost/assign/ptr_list_of.hpp>
// ...
const boost::ptr_vector<int> pv = boost::assign::ptr_list_of<int>(1)(2)(3);
|
3,105,798 | 3,106,307 | Why must the copy assignment operator return a reference/const reference? | In C++, the concept of returning reference from the copy assignment operator is unclear to me. Why can't the copy assignment operator return a copy of the new object? In addition, if I have class A, and the following:
A a1(param);
A a2 = a1;
A a3;
a3 = a2; //<--- this is the problematic line
The operator= is defined ... | Strictly speaking, the result of a copy assignment operator doesn't need to return a reference, though to mimic the default behavior the C++ compiler uses, it should return a non-const reference to the object that is assigned to (an implicitly generated copy assignment operator will return a non-const reference - C++03... |
3,105,857 | 3,105,890 | Visual Studio 2010 indentation after for loop | Why am I getting this behavior right after the if block? Am I missing something?
for (;;)
if (/*...*/)
{
// statements
}
// statements indented to match the if indentation instead of the for loop;
| About the only way to keep VS doing indentation reasonably is to always use a block to enclose the statement controlled by a for, if, while, etc. In your case that would mean:
for (;;)
{
if (/* ... */)
{
// ...
}
}
// further statements here indented to match for loop.
|
3,105,966 | 3,106,043 | Set background color of a control? (WinAPI) | How can I set the backcolor of a control (equivilant of control.backcolor in .Net). I tried setBKColor with no luck.
ex: TabHwnd = createWindowEx(NULL,WC_TAB....
then how could I set the back color of TabHwnd?
Thanks
| Windows will generate a message when it's painting the background of a control, and it is up to your program to respond to the message appropriately.
WM_CTLCOLORBTN
WM_CTLCOLOREDIT
WM_CTLCOLORDLG
WM_CTLCOLORLISTBOX
WM_CTLCOLORSCROLLBAR
WM_CTLCOLORSTATIC
|
3,106,015 | 3,106,023 | How do I increment an enum in VS C++ 6.0? | I copy and pasted some code that increments an enum:
myenum++;
This code worked fine as it was compiled in VS.NET C++ 2003
I am now developing in VS 6.0 and get the error:
error C2676: binary '++' : 'enum
ID' does not define this
operator or a conversion to a type
acceptable to the predefined operator
How... | Please try to convert to int, add one (+1) and convert back to the enum.
|
3,106,026 | 3,106,060 | Is there a stoll()/stroll() (string to long long) alternative in Visual Studio 2008 | Is there an alternative, either built into windows or apache license compatible, to stoll() for Visual Studio 2008. Even installing the windows 7 platform SDK does not add stoll() to the string header.
On unix the same function is be called strtoll().
| You can use _strtoi64. It's declared in stdlib.h.
long long num = _strtoi64(str, NULL, 10);
Similarly to strtoll, you can pass a char ** endptr as a second parameter. If so, *endptr will be set to the first invalid character (which may be the normal null-terminator).
|
3,106,038 | 3,106,068 | Polymorphism: Accessing inherited class variable | I have a class that is inherited from an abstract base class.
class CStateBase
{
friend class CApplication;
friend class CGraphics;
virtual int Update() =0;
};
class CStateTitle: private CStateBase
{
friend class CApplication;
friend class CGraphics;
CApplication *f_App;
int m_iR;
int Update();
CS... | The best way is to abstract the access of m_iR into some virtual function.
Another choice would be to move m_iR from CStateTitle into CStateBase. This only makes sense if every class needs an m_iR.
A last resort would be to do a dynamic cast:
CStateBase *csb = ...;
CStateTitle *cst = dynamic_cast<CStateTitle *>(csb);... |
3,106,042 | 3,106,058 | Is there a simple library for C++ to draw to the screen? | I'm just starting out in C++ programming and I want to try creating a space invaders clone in C++, I want to avoid using game libraries and things that would solve a lot of the problems (like game loop and vector maths etc) so I can tackle these myself, but, I have no idea how to begin drawing things to a screen.
I was... | I recommend either Allegro or SDL, even though they are mostly 2D:
Allegro:
http://alleg.sourceforge.net/
SDL:
http://www.libsdl.org/
|
3,106,188 | 3,106,232 | Programmatically Save an Excel File Using OLE | How do you programmatically save an excel workbook using OLE and C++ Builder?
I'm guessing it might be something like:
Variant excel = Variant::CreateObject("Excel.Application");
excel.OleProcedure("Save"); // but how might you specify the file name
| Oh just found the answer from here:
excel.OlePropertyGet(”Workbooks”).OlePropertyGet(”Item”,1).OleProcedure(”SaveAs”,”d:\\case1.xls”);
First you get the workbooks object followed by the workbook. Then you can do a SaveAs.
|
3,106,206 | 3,106,218 | Template object as static member of the template class | Imagine the following template class (setter and getter for the member _t omitted):
template<class T>
class chain
{
public:
static chain<T> NONE;
chain()
: _next(&NONE)
{}
~chain() {}
chain<T>& getNext() const
{
return *_next;
}
void setNext(chain<T>* next)
{
if(next && next != this)
... | You still need to define that outside the class just like a non-template class. Just like in a non-template class, you have only declared NONE inside the class definition and still need to define it:
template<class T>
class chain
{
// the same as your example
};
// Just add this
template <class T>
chain<T> chain<... |
3,106,482 | 3,106,486 | template fails to compile: 'double' is not a valid type for a template constant parameter | template<typename T, T Min>
class LowerBoundedType {};
template<typename T> class vectorelement {};
template<> class vectorelement<Categorical> { typedef LowerBoundedType<double, 0.0> type; };
with error:
error: 'double' is not a valid type for a template constant parameter
| The only numeric types valid for a nontype template parameter are integers and enumerations. So, you can't have a nontype template parameter of type double.
|
3,106,517 | 3,109,770 | Make child windows inherit parent background color? | Is there a way for windows created with WS_CHILD to inherit the parent's background color rather than default to Dialog Color? I'm trying to do this for a tab control, mainly the part that extends due to the tabs not filling up the area. I want this color to be the parent window's BG.
Thanks
| For the "content" of the tab, you would call EnableThemeDialogTexture (Visual Styles can have complex tab content backgrounds), for the area to the right of the actual tabs I think you might have to owner draw (TCS_OWNERDRAWFIXED style) unless just using the TCS_RIGHTJUSTIFY style is enough.
|
3,106,731 | 3,106,776 | How to check current mouse button state using Win32/User32 library? | I know how to stimulate clicks using User32 SendInput method and what I need is a similar User32 method but to obtain the current mouse button state.
Something similar to:
public static extern bool GetCursorPos(ref System.Drawing.Point lpPoint);
Function GetCursorPos gives me the current cursor position. What I need i... | There's a method called GetAsyncKeyState. The method signature looks like this:
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(UInt16 virtualKeyCode);
Then you simply call it passing the left mouse key code (VK_LBUTTON = 0x01) and off you go.
More information directly from MSDN.
|
3,106,740 | 3,106,799 | timeval to string (converting between the two) | I'm trying to pull the two components out of a timeval struct and place them into strings.
I'm not having much luck with this. I've attempted casting and converting first to a long and then to a string. I need the most efficient way to do this.
Any ideas? I do NOT want to convert to another data structure first (localt... | Boost's lexical_cast should be reasonably fast.
Edit:
Let me elaborate. Here's an example of its usage:
std::string strSeconds = lexical_cast<std::string>(time.tv_sec);
std::string strMicroSec = lexical_cast<std::string>(time.tv_usec);
For more complicated string formatting, the Boost documentation recommends the bas... |
3,106,767 | 3,106,778 | A question about cin in C++ | When I declare int weight and then input a double value 165.1 a 2nd cin >> height; doesn't work and there is no any error message. Can you tell me why?
VS2010 Console Application used.
#include <iostream>
using namespace std;
const double lbs_to_kg = 2.2046, inches_to_meter = 39.370;
int main()
{
int weight, he... | If you try to have cin extract data into a variable that can't hold it, the data is left in the input stream and cin is flagged as having failed. You need to check if it's failed with !cin, and use cin.clear() to clear the fail flag so you can read again (future extract operations will automatically fail until the flag... |
3,106,882 | 3,106,947 | C++ windows32 winsock UDP routing? | In C++ using Windows32 using windows socket library using UDP is there a way to give a client routing information to another client to establish a connection between clients without having to route through the server
Clarification:
server - waits for computers and gives routing info - a detached server
client - sends a... | Short answer: no
Long answer: yes --- but you have to use IPPROTO_IP, not IPPROTO_UDP. Use IP_OPTIONS option in setsockopt() to set source routing.
|
3,106,958 | 3,107,336 | Simple question regarding an equation inside of a function | Hey, so basically I have this issue, where I'm trying to put an equation inside of a function however it doesn't seem to set the value to the function and instead doesn't change it at all.
This is a predator prey simulation and I have this code inside of a for loop.
wolves[i+1] = ((1 - wBr) * wolves[i] + I * S * ra... | I was using an integer as an argument for a double.
|
3,107,005 | 3,107,053 | Does the license on the .NET framework allow distribution of derivative forms of it's code? | I'd like to mimic a .NET class signature (and possibly some major pieces of implementation) in a C++ application. I plan on releasing said application under the Boost Software License. Specifically, I'd like to use the TimeSpan and DateTime interfaces, as well as some implementation I found using the handy dandy Reflec... | You cannot redistibute modifications of their BCL implementation (mscorlib) for commercial purposes. It is available under the Shared Source license, which allows you to use it for academic/personal use only.
The ECMA 335 standard requires that the BCL be implemented in any CLR implementation though, so you can duplica... |
3,107,246 | 3,107,289 | Reference to a Two-Dimesional Array | I want to implement a function with OpenGL to render a cylinder in C++. The signature of my function is as follows:
#define POINTS_NUM 15
#define DEMESION 3
void drawCylinder( int slices, int segments, GLfloat (&vertices)[ POINTS_NUM ][ DEMESION ] );
I want to use a reference to a two-dimensional array to lim... | Your first declaration is fine. Seems to be you have defined vase in a header file.
|
3,107,441 | 4,821,441 | Prevent Up-Down control for Tab Control? | As documented:
"If not all tabs can be shown at once, the tab control displays an up-down control so that the user can scroll additional tabs into view."
http://msdn.microsoft.com/en-us/library/bb760550%28VS.85%29.aspx
I don't want this. I don't want an up down control to show if I have too many and I don't want mul... | There's no style for that, so i believe the only way is a bit of hacking. From what i can see with my Spy++, the updown control is a true child control of the tab control with id = 1. So, you can actually hide it with ShowWindow().
|
3,107,697 | 3,107,719 | What is the meaning of new int[25,2]? | What is the meaning of using the second parameter with a comma in the below code?
int *num = new int[25,2];
| That's the comma operator in action: it evaluates it's operand and returns the last one, in your case 2.
So that is equivalent with:
int *num = new int[2];
It's probably safe to say that the 25,2 part was not what was intended, unless it's a trick question.
Edit: thank you Didier Trosset.
|
3,107,699 | 3,107,790 | Is Visual C++ as powerful as gcc? | My definition of powerful is ability to customize.
I'm familiar with gcc I wanted to try MSVC. So, I was searching for gcc equivalent options in msvc. I'm unable to find many of them.
controlling kind of output
Stop after the preprocessing stage; do not run the compiler proper.
gcc: -E
msvc: ???
Stop after the stage o... | MSVC is an IDE, gcc is just a compiler. CL (the MSVC compiler) can do most of the steps that you are describing from gcc's point of view. CL /? gives help.
E.g.
Pre-process to stdout:
CL /E
Compile without linking:
CL /c
Generate assembly (unlike gcc, though, this doesn't prevent compiling):
CL /Fa
CL is really just... |
3,107,771 | 5,681,448 | Pixel coordinates to 3D line (opencv) | I have an image displayed on screen which is undistorted via cvInitUndistortMap & cvRemap (having done camera calibration), and the user clicks on a feature in the image. So I have the (u,v) pixel coordinates of the feature, and I also have the intrinsic matrix and the distortion matrix.
What I'm looking for is the eq... | This is a bit old question but still might be usefull for someone.
All lines go through the point (0,0,0), so:
line.x0 = 0;
line.y0 = 0;
line.z0 = 0;
direction vector is as follows:
line.A = (u/fx) - (cx/fx);
line.B = (v/fy) - (cy/fy);
line.C = 1;
cx,cy,fx,fy are parameters from camera matrix.
Equations are explained... |
3,107,924 | 3,108,000 | C++ Type Casting: benefit of using explicit casts? | What are benefits of using these operators instead of implicit casting in c++?
dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
Why, where, in which situation we should use them? And is it true that they are rarely used in OOP?
| From the list of casts you provided, the only one that makes sense to be used to supstitute an implicit cast is the static_cast.
dynamic_cast is used to downcast a superclass into its subclass. This cannot happen implicitly and is actually something that is not that rare in OOP. static_cast could be used in such a cas... |
3,107,974 | 3,108,006 | Call a C++ base class method automatically | I'm trying to implement the command design pattern, but I'm stumbling accross a conceptual problem. Let's say you have a base class and a few subclasses like in the example below:
class Command : public boost::noncopyable {
virtual ResultType operator()()=0;
//Restores the model state as it was before command'... | It looks as if you can benefit from the NVI (Non-Virtual Interface) idiom. There the interface of the command object would have no virtual methods, but would call into private extension points:
class command {
public:
void operator()() {
do_command();
add_to_undo_stack(this);
}
void undo();
private... |
3,108,142 | 3,108,173 | C++: proper inlining syntax | Is it preferred to define inline methods like:
// math.h
class Math
{
public:
inline static int sum(int a, int b)
{
return a + b;
}
};
or
// math.h
class Math
{
public:
static int sum(int a, int b);
};
// math.cpp
inline int Math::sum(int a, int b);
{
return a + b;
}
and why? Is there an... | Inlining is entirely up to the compiler. The inline keyword, like the old C register keyword is a suggestion to the compiler to do some optimisation.
However, compiler writers know so much more than we lesser beings about their target architectures that this is really unnecessary.
Because of that, I don't ever use inli... |
3,108,220 | 3,108,279 | Porting windows code, what to use instead of __int64 _tmain and _TCHAR*? | I'm currently porting some windows code and trying to make it available for use in Ubuntu. The project was originally compiled in VC++ without any issues. Also I should note that this only needs to work in Ubuntu, but more platform independent ideas are certainly welcome.
Most of the code is easy to port as it is mostl... | For the 64-bit:
#include <inttypes.h>
typedef int64_t __int64;
As for the TCHAR problem. I actually find TCHARs rather useful so I have a file with all the _t functions I use in it.
e.g
#ifdef UNICODE
#define _tcslen wcslen
#define _tcscpy wcscpy
#define _tcscpy_s wcscpy_s
#define _tcsncpy wcsncpy
#def... |
3,108,282 | 3,108,294 | Unicode supported isdigit and isspace function | I have the following code.
// mfc.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "mfc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#include <cctype>
#include <string>
#include <sstream>
#include <tchar.h>
#include <iostream>
#include <Strsafe.h>
#include <algorithm>
#incl... | iswdigit?
http://www.opengroup.org/onlinepubs/007908775/xsh/iswdigit.html
http://msdn.microsoft.com/en-us/library/fcc4ksh8(VS.71).aspx
also, look up iswspace ;)
|
3,108,311 | 3,108,528 | Undefined references to functions with C++ template methods | Why am I getting undefined references to the methods in this class when I call them? Will I be forced to include the implementation in the header file or is there another way to do this better?
class MathHelper
{
public:
/*!
Represents the ratio of the circumference of a circle to its diameter,
spec... | I think the explanation and answer to your question is this C++ faq lite answer and the next ones
Basically, as templates are patterns to instanciate, any code unit needing it must know how to instanciate it. Therefore, the simpliest way is to define your templates in header files (like boost does). The C++ faq lite gi... |
3,108,340 | 3,108,356 | Double Pointer Usage | Please take a look at following code:
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct MyType{
int num1;
};
void test(MyType **src)
{
MyType *ret=new MyType;
ret->num1=666;
*src=ret;
}
int main(){
MyType *mSrc;
test(&mSrc);
printf("%d Address\n",mSrc);
printf("%d Value \n",mSrc->num... | void test(MyType *src)
Here src is just a local variable within the test function, it's a copy of the pointer you passed to it. Assigning to a local variable doesn't have any effect on the caller.
If you wanted src to refer to the same variable you passed in, use a reference
void test(MyType *&src)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.