question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,514,158 | 2,514,199 | How to directly access a certain part of a text file in g++? | I have a text file containing a number of records. Each record is stored on a single line that is 100 characters long.
Let's say I want to directly access the nth record. I could do it using a for loop, reading in n lines until I get to the record.
But how could I access it directly?
| If the each line is exactly 100 characters long and the line ending is always \n (i.e. no \r\n stuff) and there's no blank lines and people won't use 1 tab for 8 spaces etc. you can use (with ifstream)
fin.seekg(101 * n, ios::beg); // Assume the initial record has n=0.
or (with FILE*)
fseek(f, 101 * n, SEEK_SET);
If... |
2,514,278 | 2,575,579 | Scalable memory allocator experiences | I am currently evaluating a few of scalable memory allocators, namely nedmalloc and ptmalloc (both built on top of dlmalloc), as a replacement for default malloc / new because of significant contention seen in multithreaded environment. Their published performance seems to be good, however I would like to check what ar... | I have implemented NedMalloc into our application and I am quite content with the results. The contention I have seen before was gone, and the allocator was quite easy to plug in, even the general performance was very good, up to the point the overhead of memory allocations is out application is now close to unmesurabl... |
2,514,350 | 2,522,282 | C++ IDE for Linux with smart reference searching | Is there an IDE supporting C++ with REALLY smart searching of references? By 'reference' I mean usage of a class (or its member), variable, function in the whole Project or Workspace.
There's lots of IDE providing it. Some of them seem just to search for the text with same name giving lots of stuff, others are smarter ... | I think Qt-Creator can help you. There few new features added in new preview 2.0.
|
2,514,394 | 2,515,008 | Declare module name of classes for logging | I currently am adding some features to our logging-library. One of these is the possibility to declare a module-name for a class that automatically gets preprended to any log-messages writing from within that class. However, if no module-name is provided, nothing is prepended. Currently I am using a trait-class that ha... |
I would like this to be possible within the class.
This is not possible with your approach, explicit specializations have to be declared in the namespace of which the template is a member.
You don't say how the actual using code looks like, but you should be able to let name and overload resolution work for you (e.g.... |
2,514,401 | 2,514,468 | Getting name and type of a struct field from its object | For example, I have a struct which is something like this:
struct Test
{
int i;
float f;
char ch[10];
};
And I have an object of this struct such as:
Test obj;
Now, I want to programmatically get the field names and type of obj. Is it possible?
This is C++ BTW.
| You are asking for Reflection in C++.
|
2,514,535 | 2,514,921 | How to get a filetype icon in Windows using C/C++? | I am looking for a C/C++ code which can get icon for a given filetype (eg. .doc, .pdf) on Windows. I need to make an application which will display a list of files and I need to have the file icons corresponding to those files.
I have seen C# code for the same but I have never worked with C# and don't think that I can ... | I've found this: http://msdn.microsoft.com/en-us/magazine/cc301425.aspx
So you basically call SHGetFileInfo with SHGFI_USEFILEATTRIBUTES and any file name/path (it doesn't matter if it doesn't exist), and it writes the filetype info to a SHFILEINFO.
|
2,514,539 | 2,514,554 | Is it a good idea to return " const char * " from a function? | Now I have a function that has to return a string. I saw a particular implementation where he returns a const char * from the function.
Something like this:
const char * GetSomeString()
{
........
return somestlstring.c_str();
}
SomeOtherFoo ()
{
const char * tmp = GetSomeString();
string s = tmp;
}
Now... | Depending on what somestlstring is and what is being done there.
If it is a local variable you are returning a pointer into memory that is being released when GetSomeString completes, so it is a dangling pointer and an error.
It all boils down to the lifetime of somestlstring and the operations you perform on it. The p... |
2,515,261 | 2,515,285 | What are the definitions for LPARAM and WPARAM? | I know I'm being lazy here and I should trawl the header files for myself, but what are the actual types for LPARAM and WPARAM parameters? Are they pointers, or four byte ints? I'm doing some C# interop code and want to be sure I get it working on x64 systems.
| LPARAM is a typedef for LONG_PTR which is a long (signed 32-bit) on win32 and __int64 (signed 64-bit) on x86_64.
WPARAM is a typedef for UINT_PTR which is an unsigned int (unsigned 32-bit) on win32 and unsigned __int64 (unsigned 64-bit) on x86_64.
MSDN link
|
2,515,494 | 2,515,592 | Read in double type from txt file - C++ | I'm in the midst of a university project and have decided to implement a method that can accept information from a text file (in this instance called "locations.txt"). input from the text file will look like this:
London
345
456
Madrid
234
345
Beinjing
345
456
Frankfurt
456
567
The function looks like this currently (... | std::string city;
double lat, lgt;
while( (inputFile >> city ) && (inputFile >> lat) && (inputFile >> lgt ) ) {
// do something with values
}
|
2,515,527 | 2,515,582 | Use of iterators over array indices | I just wanted to know what is the main advantage of using the iterators over the array indices. I have googled but i am not getting the right answer.
| I presume you are talking about when using a vector, right?
The main advantage is that iterator code works for all stl containers, while the array indexing operator [] is only available for vectors and deques. This means you are free to change the underlying container if you need to without having to recode every loop... |
2,515,722 | 2,515,793 | Handling Complex Rules in GUI applications (C++ or C#) | Im working on a dialog box in which several rules must be satisfied before the OK button is enabled.
Currently any action on the page such as entering data or selecting an item from a drop down list (amongst other things) calls a single function called ProcessEvent() - this function handles all logic and either enables... | I would split your if/else statements into multiple functions, and do an &= on the parameter you send to EnableNext. You should be calling EnableNext only once.
So, for example:
// in CWorkStation::ProcessEvent
bool enableNext = true; // start with true
enableNext &= Condition1(); // of course pick better names than C... |
2,515,922 | 2,518,224 | avoiding enums as interface identifiers c++ OOP | I'm working on a plugin framework using dynamic loaded shared libraries which is based on Eclipse's (and probally other's) extension-point model. All plugins share similar properties (name, id, version etc) and each plugin could in theory satisfy any extension-point. The actual plugin (ie Dll) handling is managed by an... | What is the problem of the enum ? The lack of extensibility.
How to have extensibility and yet retain identification ? You need a full blown object, preferably with a specific type.
Basically you can get away with:
class IPluginId
{
public:
virtual IPluginId* clone() const = 0;
virtual ~IPluginId();
bool operato... |
2,515,966 | 2,515,988 | What is the point of STL? | I've been programming c++ for about a year now and when i'm looking about i see lots of references to STL.
Can some one please tell me what it does?
and the advantages and disadvantageous of it?
also what does it give me over the borlands VCL or MFC?
thanks
| It's the C++ standard library that gives you all sorts of very useful containers, strings, algorithms to manipulate them with etc.
The term 'STL' is outdated IMHO, what used to be the STL has become a large part of the standard library for C++.
If you are doing any serious C++ development, you will need to be familiar ... |
2,516,165 | 3,537,372 | Using time facets on universal_time | on boost, to create a time facet to format an specified time we use the folowing:
boost::local_time::local_time_facet* facet = new boost::local_time::local_time_facet("%Y%m%d %H:%M:%S.%f");
std::stringstream date_stream;
date_stream.imbue(std::locale(date_stream.getloc(), facet));
date_stream << boost::local_time::loca... | I know that by now scooterman has either found the answer or doesn't care anymore (:D), but in the case that someone found this question while searching (like i did), here's the answer:
boost::posix_time::ptime time(microsec_clock::universal_time());
std::stringstream ss;
boost::date_time::time_facet *facetPtr
... |
2,516,308 | 2,516,805 | Caller graph for overloaded operators in Visual Studio 2005 | Is is possible to get a callers graph for overloaded operators?
I have a simple struct with a natural ordering which I have represented by overloading the relational operators. Looking back through the code, it appears that I made a mistake in defining operator >. I had set the greater than to simply return the negatio... |
Unless the class of which val1 and val2 are instances of has base classes that themselves implement operator> I suggest you remove your definition of operator> from the header and cpp files and recompile. This should give you a list of all calls to operator> guaranteed by the compiler.
Boost.Operators may help to avo... |
2,516,322 | 2,516,395 | How can I find out how much memory is physically installed in Windows? | I need to log information about how much RAM the user has. My first approach was to use GlobalMemoryStatusEx but that only gives me how much memory is available to windows, not how much is installed. I found this function GetPhysicallyInstalledSystemMemory but its only Vista and later. I need this to work on XP. Is the... | EDIT: I'd use steelbytes' answer, but if you can't use WMI For some reason, you can do this:
I don't believe Windows versions prior to Vista track this information -- you'd have to do some system specific BIOS or Motherboard enumeration to find the true value prior to Vista. Your best bet is to call the new API, GetPhy... |
2,516,337 | 2,516,363 | What's the relationship between header files and library files in c++? | Why do we need to add both includes and libs to the compilation?
Why doesn't the libs wrap everything in it?
| A header file (usually) only contains declarations for classes and functions. The actual implementations are built from CPP files. You can then link against those implementations with only the header declarations available.
|
2,516,413 | 2,516,504 | Visual Studio Recompiles Project Every Time I Try to Run it | I have a Visual Studio 2005 solution. Every time I try to run the startup project (C++), the project gets build again, although I did not make any change.
How can I get the normal, sane behaviour, where projects get built only when needed?
How can I debug the problem further?
Thanks,
| On at least one occasion I've had files appear that had a last-write-time that was some time in the future. Presumably this occurred because either my computer's clock was wrong when the file was last written or the file came from another computer whose clock was wrong.
That can cause this problem, so check the timest... |
2,516,631 | 2,516,650 | Cannot initialize non-const reference from convertible type | I cannot initialize a non-const reference to type T1 from a convertible type T2. However, I can with a const reference.
long l;
const long long &const_ref = l; // fine
long long &ref = l; // error: invalid initialization of reference of
// type 'long long int&' from expressio... | An integer promotion results in an rvalue. long can be promoted to a long long, and then it gets bound to a const reference. Just as if you had done:
typedef long long type;
const type& x = type(l); // temporary!
Contrarily an rvalue, as you know, cannot be bound to a non-const reference. (After all, there is no actua... |
2,516,866 | 2,517,302 | struct method linking | I'm updating some old code that has several POD structs that were getting zero'd out by memset (don't blame me...I didn't write this part). Part of the update changed some of them to classes that use private internal pointers that are now getting wiped out by the memset.
So I added a [non-virtual] reset() method to the... | I think that your problem (and I don't have a standards quote to back this up) is that because your struct doesn't have a name, your member function also does not have a globally identifiable name.
Although you're allowed to use a typedef name to introduce a member function definition, that member function must be part... |
2,516,896 | 2,517,305 | Presenting MVC to Old C++ Spaghetti Coders? | I wish to present the idea of MVC to a bunch of old C++ spaghetti coders (at my local computer club).
One of them that has alot of influence on the rest of the group seems to finally be getting the idea of encapsulation (largely due in part to this website).
I was hoping that I could also point him in the right dir... | Don't start off with MVC. Start off with Publish / Subscribe (AKA the "listener" pattern).
Without the listener pattern fully understood, the advantages of MVC will never be understood. Everyone can understand the need to update something else when something changes, but few think about how to do it in a maintainable... |
2,516,960 | 2,516,994 | C++ using this pointer in constructors | In C++, during a class constructor, I started a new thread with this pointer as a parameter which will be used in the thread extensively (say, calling member functions). Is that a bad thing to do? Why and what are the consequences?
My thread start process is at the end of the constructor.
| The consequence is that the thread can start and code will start executing a not yet fully initialized object. Which is bad enough in itself.
If you are considering that 'well, it will be the last sentence in the constructor, it will be just about as constructed as it gets...' think again: you might derive from that c... |
2,516,965 | 2,520,341 | How to setup directories in Visual Studio when using boost? | I have introduced boost to our code base, on my machine I created a boost directory called Thirdparty.Boost and added that as an additional include directory in my Visual Studio setting, all is fine.
However I now want to check in my changes, so the rest of the team can get them. Inorder to build the code they would ne... | What about adding an environment variable on each of your developer's machines:
CL=-I<...the_boost_directory...>
i.e. on your machine:
CL=-IThirdparty.Boost
The MS compiler adds the value of the environment variable CL to its command line, so this should do the trick for you.
|
2,517,019 | 2,517,626 | Elegant way of parsing Data files for Simulation | I am working on this project where I need to read in a lot of data from .dat files and use the data to perform simulations. The data in my .dat file looks as follows:
DeviceID InteractingDeviceID InteractionStartTime InteractionEndTime
1 2 1101 1105
1,2 1101 and 1105 are t... | Your approach seems to be correct given the information you've provided.
I'm assuming you'd be creating a class something like:
class device {
public:
int id;
vector<interaction> interactions;
void add_interaction(interaction add_me); // uses vector::insert
};
with
typedef struct interaction_t {
int ... |
2,517,050 | 2,517,110 | C++: Construction and initialization order guarantees | I have some doubts about construction and initialization order guarantees in C++. For instance, the following code has four classes X, Y, Z and W. The main function instantiates an object of class X, which contains an object of class Y, and derives from class Z, so both constructors will be called. Additionally, the co... | In all classes construction order is guaranteed: base classes, as specified from left to right followed by member variables in the order declared in the class definition. A class's constructor body is executed once all of its bases' and members' constructions have completed.
In your example X is derived from Z and cont... |
2,517,245 | 2,517,455 | Why, really, deleting an incomplete type is undefined behaviour? | Consider this classic example used to explain what not to do with forward declarations:
//in Handle.h file
class Body;
class Handle
{
public:
Handle();
~Handle() {delete impl_;}
//....
private:
Body *impl_;
};
//---------------------------------------
//in Handle.cpp file
#include "Handle.... | To combine several answers and add my own, without a class definition the calling code doesn't know:
whether the class has a declared destructor, or if the default destructor is to be used, and if so whether the default destructor is trivial,
whether the destructor is accessible to the calling code,
what base classes ... |
2,517,362 | 2,517,387 | Why would you avoid C++ keywords in Java? | A popular editor uses highlighting to help programmers avoid using C++ keywords in Java. The following words are displayed using the same colors as a syntax error:
auto delete extern friend inline redeclared register signed sizeof
struct template typedef union unsigned operator
Why would this be considered important?
| To avoid confusion. The largest migration path in the entire industry over the last 15 years was from C++ to Java. Thus, it would be wise to avoid using those words in a new context where they no longer mean anything.
|
2,517,484 | 2,517,574 | How can I pass a C++ member function to a C API as a parameter | In my C++ program, I need to call this c API:
GConn* gnet_conn_new (const gchar *hostname,
gint port,
GConnFunc func);
where GConnFunc is defined as:
void (*GConnFunc) (GConn *conn);
My question is if I have a C++ class and have a member function like:
Class A {
public:
... | Most APIs provide a pointer-sized 'user data' argument, which would look like this:
GConn* gnet_conn_new (const gchar *hostname,
gint port,
GConnFunc func,
void* user_data);
This would allow you to pass an instance in user_data and have your C function forward t... |
2,517,592 | 2,518,056 | Multithreading: apache portable runtime vs boost::thread? | Which way is better for a novice student who has never used boost?
When a new standard arrives, the answer will be obvious, but now I have doubts. Pro for boost is that it's much closer to future standard.
| Another pro for Boost is that it uses common C++ idioms for describing, initializing, running, and joining threads (using idioms like RAII and allowing the use of functors and similar C++-specific tools).
Lower-level libraries like APR rely on the use of C-like idioms, which for a C++ developer can prove to be more err... |
2,517,946 | 2,517,970 | How to swap out a memory block? | How to make a block of memory allocated by malloc() or new:
immediately swapped out,
or lazily initialized.
In fact, I'm trying to reserve an address space. How to accomplish this?
PS. How to verify, from the user space, if a memory block is swapped out?
| To reserve a chunk of address space:
On unix, sbrk() or mmap().
On Windows, VirtualAlloc().
|
2,518,254 | 2,518,729 | 32bit to 64bit inline assembly porting | I have a piece of C++ code (compiled with g++ under a GNU/Linux environment) that load a function pointer (how it does that doesn't matter), pushes some arguments onto the stack with some inline assembly and then calls that function, the code is like :
unsigned long stack[] = { 1, 23, 33, 43 };
/* save all the registe... | While it shouldn't be much of a problem to call a function pointer with the appropriate arguments in inline assembly, I don't think recoding this naively in x64 will help you, because the calling conventions to be used are very probably different (defaults for 32bit and 64bit linux are definitely different). Have a loo... |
2,518,305 | 2,518,358 | What is the difference between set and hashset in C++ STL? | When should I choose one over the other?
Are there any pointers that you would recommend for using the right STL containers?
| hash_set is an extension that is not part of the C++ standard. Lookups should be O(1) rather than O(log n) for set, so it will be faster in most circumstances.
Another difference will be seen when you iterate through the containers. set will deliver the contents in sorted order, while hash_set will be essentially rando... |
2,518,796 | 2,518,839 | Resolving namespace conflicts | I've got a namespace with a ton of symbols I use, but I want to overwrite one of them:
external_library.h
namespace LottaStuff
{
class LotsOfClasses {};
class OneMoreClass {};
};
my_file.h
using namespace LottaStuff;
namespace MyCustomizations
{
class OneMoreClass {};
};
using MyCustomizations::OneMoreClass;
my_file.... | The entire point of namespaces is defeated when you say "using namespace".
So take it out and use namespaces. If you want a using directive, put it within main:
int main()
{
using myCustomizations::OneMoreClass;
// OneMoreClass unambiguously refers
// to the myCustomizations variant
}
Understand what usin... |
2,518,816 | 2,518,864 | What's the usage if I provide an implementation for a pure virtual function in C++ | I know that it's OK for a pure virtual function to have an implementation. However, why it is like this? Is there conflict for the two concepts? What's the usage? Can any one offer any example?
| Was addressed in GotW #31. Summary:
There are three main reasons you might
do this. #1 is commonplace, #2 is
pretty rare, and #3 is a workaround
used occasionally by advanced
programmers working with weaker
compilers.
Most programmers should only ever use #1.
... Which is for pure virtual destructors.
|
2,518,921 | 2,519,007 | Adding an inheritance to an Qt designed object | I have a problem and I want to implement the MVC pattern to my QT application, that's why I need for example to inherite in my QTableWidget about another class like
myClass
{
myMethod();
}
but our QTableWidget is contained by our Mainwidows that is designed by the QT designer and generate an ui_MainWindow class !... | You can use custom objects in QDesigner. Right click on the widget that you want to have as an instance of a something that is not available in designer and select "Promote to ...". In that dialog you can enter a custom class and a include file where the declaration for your class can be found.
BUT Qt implements uses ... |
2,518,969 | 2,519,101 | GCC, Unicode and __FUNCTION__ | I'm trying to make my project compile under GCC (Visual Studio compiles it flawlessly).
I have a custom assert function which throws a wstring message. A part of it is the _ _FUNCTION__ macro, which I "unicodize" using the WIDEN macro from MSDN
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
It compiles okay in MS... | In GCC __FUNCTION__ is a non-standard extension. To quote: GCC Online Docs
In GCC 3.3 and earlier, in C only,
__FUNCTION__ and __PRETTY_FUNCTION__ were treated as string literals; they
could be used to initialize char
arrays, and they could be concatenated
with other string literals. GCC 3.4
and later treat ... |
2,518,979 | 2,519,011 | How to transform a vector<int> into a string? | I am trying to pass a value from C++ to TCL. As I cannot pass pointers without the use of some complicated modules, I was thinking of converting a vector to a char array and then passing this as a null terminated string (which is relatively easy).
I have a vector as follows:
12, 32, 42, 84
which I want to convert ... | What about:
std::stringstream result;
std::copy(my_vector.begin(), my_vector.end(), std::ostream_iterator<int>(result, " "));
Then you can pass the pointer from result.str().c_str()
|
2,519,325 | 2,519,349 | C++ method parameter passed by reference - memory question | Assume,
void proc(CString& str)
{
str = "123";
}
void runningMethod()
{
CString str="ABC";
proc(str);
}
I understand that at the exit of runningMethod str will be deallocated automatically; in this case, how does C++ delete the old data ("ABC")?
Thanks,
Gil.
| "ABC" was overwritten when you said = "123".
Internally, a string is an array of characters. At start, it made a new buffer that contained {'A', 'B', 'C', '\0'}. When you assigned, it just wrote '1' over the 'A', and so on.
When it destructed, it deleted the buffer.
|
2,519,529 | 2,519,551 | Reading value at an address | I'm trying to make a program that reads the value at a certain address.
I have this:
int _tmain(int argc, _TCHAR* argv[])
{
int *address;
address = (int*)0x00000021;
cout << *address;
return 0;
}
But this gives a read violation error. What am I doing wrong?
Thanks
| You can only use a pointer that points to an actual object.
If you don't have an object at address 0x00000021, this won't work.
If you want to create an object on the free store (the heap), you need to do so using new:
int* address = new int;
*address = 42;
cout << *address;
delete address;
|
2,519,564 | 2,519,875 | how to write programs using advanced OpenType features? | How could I write a simple program using OpenType tables in order to dynamically render text?
please answer in :
assembly , C , C++ , C# , java or Python (and a little WPF:-)
or introduce libraries of them.
comments and answers about text rendering system of common Operating Systems, or designing text engines compa... | I don't know if this will satisfy your needs or not, but I've used the FreeType library in the past to render TrueType text. It is quite flexible and easily ported between various platforms (Linux, Windows, OSX, etc.). Also, the licensing (BSD-style) is such that using it in commercial applications is not a problem.
|
2,519,603 | 2,519,623 | Debugging unmanaged code while debugging managed code | The .NET 3.5 application I am working on consists of bunch of different solutions. Some of these solutions consist of managed code(C#) and others have unmanaged code(C++). Methods written in C# communicate with the ones written in C++. I am trying to trace the dependencies between these various functions and I thought ... | By default a managed project will only start the debugger with managed debugging enabled. It doesn't consider that there are unmanaged projects in the same solution. In order to debug both you need to explicitly enable unmanaged code debugging.
Right Click on the project and select properties
Go to the Debug tab
Che... |
2,519,627 | 2,519,651 | isalpha(<mychar>) == true evaluates to false? | string temp is equal to "ZERO:\t.WORD\t1" from my debugger. (the first line of my file)
string temp = RemoveWhiteSpace(data);
int i = 0;
if ( temp.length() > 0 && isalpha(temp[0]) )
cout << "without true worked" << endl;
if ( temp.length() > 0 && isalpha(temp[0]) == true )
cout << "with true worked" << endl;
... | The is* functions are only guaranteed to return a non-zero value if true, NOT necessarily a 1. A typical implementation is table based, with one entry in the table for each character value, and a set of bits defining which bit means what. The is* function will just AND the right bitmask with the table value, and return... |
2,519,645 | 2,519,735 | Trouble calculating correct decimal digits | I am trying to create a program that will do some simple calculations, but am having trouble with the program not doing the correct math, or placing the decimal correctly, or something. Some other people I asked cannot figure it out either.
Here is the code: http://pastie.org/887352
When you enter the following data:
... | I changed your for loop to this:
cout << (i+1) << " $" << wage*52 << "\n";
wage = wage * (1+(raise/100.0));
And it did worked!. I see you didn't understand the language of the problem.
|
2,519,727 | 2,520,385 | Linking Boost to my C++ project in Eclipse | I'm trying to get the Boost library working in my C++ projects in Eclipse. I can successfully build when using header-only libraries in Boost such as the example simple program in the "Getting Started" guide using the lambda header.
I cannot get my project to successfully link to the regex Boost library as shown later ... | I just went through the whole process of installing MinGW, compiling boost and installing Eclipse CDT and I'm able to compile simple programs using boost:regex. I'll write down all the steps. I hope that can be of help.
I've installed MinGW and MSYS in their default location.
Here are the step I took to build boost:
D... |
2,519,851 | 2,519,862 | How to deal with Warning C4100 in Visual Studio 2008 | For some reason my Visual Studio 2008 began to show warnings for code like:
"int main( int argc, char **argv)", which is really annoying.
The detailed warning ouputs are (you can ignore the line numbers):
1>.\main.cpp(86) : warning C4100: 'argv' : unreferenced formal parameter
1>.\main.cpp(86) : warning C4100: 'argc'... | If the parameters are unreferenced, you can leave them unnamed:
int main(int, char**)
{
}
instead of
int main(int argc, char** argv)
{
}
If you really want just to suppress the warning, you can do so using the /wd4100 command line option to the compiler or using #pragma warning(disable: 4100) in your code.
This is a... |
2,520,130 | 2,520,156 | Why are structs not allowed in template definitions? | The following code yields an error error: ‘struct Foo’ is not a valid type for a template constant parameter:
template <struct Foo>
struct Bar {
};
Why is that so?
template <class Foo>
struct Bar {
};
works perfectly fine and even accepts an struct as argument.
| This is just an artifact of the syntax rules - the syntax just lets you use the class or typename keywords to indicate a type template parameter. Otherwise the parameter has to be a 'non-type' template parameter (basically an integral, pointer or reference type).
I suppose Stroustrup (and whoever else he might have ta... |
2,520,413 | 2,591,731 | setcontext and makecontext to call a generic function pointer | In another question I had the problem to port the code:
unsigned long stack[] = { 1, 23, 33, 43 };
/* save all the registers and the stack pointer */
unsigned long esp;
asm __volatile__ ( "pusha" );
asm __volatile__ ( "mov %%esp, %0" :"=m" (esp));
for( i = 0; i < sizeof(stack); i++ ){
unsigned long val = stack[i]... | Finally i'm using libffi .
|
2,520,843 | 2,521,681 | operator new for array of class without default constructor | For a class without default constructor, operator new and placement new can be used to declare an array of such class.
When I read the code in More Effective C++, I found the code as below(I modified some part).....
My question is, why [] after the operator new is needed?
I test it without it, it still works. Can any... | I'm surprised that Effective C++ would be advising you to use something as hackish as a void*.
new[] does a very specific thing: it allocates a dynamically sized array. An array allocated with it should be passed to delete[]. delete[] then reads a hidden number to find how many elements are in the array, and destroys t... |
2,520,900 | 2,521,703 | Portable end of line | is there any way to automatically use correct EOL character depending on the OS used?
I was thinking of something like std::eol?
I know that it is very easy to use preprocessor directives but curious if that is already available.
What I am interested in is that I usually have some messages in my applications that I com... | std::endl is defined to do nothing besides write '\n' to the stream and flush it (§27.6.2.7). Flushing is defined to do nothing for a stringstream, so you're left with a pretty way of saying mystringstream << '\n'. The standard library implementation on your OS converts \n appropriately, so that's not your concern.
Thu... |
2,521,130 | 2,521,141 | Copy hashtable to another hashtable using c++ | I am starting with c++ and need to know, what should be the approach to copy one hashtable to another hashtable in C++?
We can easily do this in java using: HashMap copyOfOriginal=new HashMap(original);
But what about C++? How should I go about it?
UPDATE
Well, I am doing it at a very basic level,perhaps the java examp... | Well, what hash table implementation are you using? There is no hash table provided by the current version of ISO C++. That said, if your hash table class does not make operator= and its copy constructor private, then it would be a reasonable assumption that both will behave as expected. If not, I'd consider it a bug.
... |
2,521,200 | 2,521,215 | overriding enumeration base type using pragma or code change | Problem:
I am using a big C/C++ code base which works on gcc & visual studio compilers where enum base type is by default 32-bit(integer type).
This code also has lots of inline + embedded assembly which treats enum as integer type and enum data is used as 32-bit flags in many cases.
When compiled this code with realvi... | I know that a lot of the windows headers use the following:
enum SOME_ENUM {
ONE = 1,
TWO = 2,
//...
FORCE_DWORD = 0x7FFFFFFF
};
|
2,521,401 | 2,521,431 | C++ Pointer member function with templates assignment with a member function of another class | class IShaderParam{
public:
std::string name_value;
};
template<class TParam>
class TShaderParam:public IShaderParam{
public:
void (TShaderParam::*send_to_shader)( const TParam&,const std::string&);
TShaderParam():send_to_shader(NULL){}
TParam value;
void up_to_shader();
};
typedef TShaderParam<float> FloatShad... | Presumably TShader::send_to_shader is a c-style function pointer?
Member functions cannot be used as function pointer callbacks - they require a this parameter.
Static member functions and global functions can be used as function pointers.
So you can either
pass the this manually as a parameter to a static function ca... |
2,521,629 | 2,521,702 | Did anyone give these smart pointers (auto_any, scoped_any, shared_any) a test drive? | I'm investigating smart pointers with "shared" functionality for Windows CE and Mobile, where the VS 2008 tr1 std::shared_ptr cannot be used (due to linkage to a v.9 dll not present on CE, obviously, if I understand it correctly).
There's a semi-old MSDN Magazine article with sources from a Microsoftie (Eric Niebler): ... | You might want to use boost::shared_ptr. As I understand it, the Boost.SmartPointer library is a header-only library, and so you can just copy over the headers you need from Boost to get everything working.
|
2,521,633 | 2,521,674 | Casting warnings in methods with variable arguments | Sorry if the question isn't correct, I'm very new in Objective-C.
I understand why this code throw the Warning: "warning: passing argument 1 of 'initWithObjectsAndKeys:' makes pointer from integer without"
NSDictionary *dictNames =
[[NSDictionary alloc] initWithObjectsAndKeys:
3, @"",
4, @"",
5, @"",nil]... | The prototype of the method you mentioned is
-(id)initWithObjectsAndKeys:(id)firstObject, ...;
Thus the first parameter must be an ObjC object. But the rest are passed by varargs. In C, any primitives can be passed as vararg arguments (think printf). Hence the compiler won't issue any warnings.
While the compiler is ... |
2,521,699 | 2,521,710 | Need help in resolving a compiler error: error: invalid conversion from ‘int’ to ‘GIOCondition’ | I have a simple cpp file which uses GIO. I have stripped out everything to show my compile error:
Here is the error I get:
My.cpp:16: error: invalid conversion from ‘int’ to ‘GIOCondition’
make[2]: *** [My.o] Error 1
Here is the complete file:
#include <glib.h>
static gboolean
read_socket (GIOChannel *gio, GIOConditi... | You can Cast it
(GIOCondition) G_IO_IN|G_IO_HUP
or
void createGIOChannel() {
GIOChannel* gioChannel = g_io_channel_unix_new(0);
// the following is the line causing the error:
GIOCondition cond = G_IO_IN|G_IO_HUP;
g_io_add_watch(gioChannel, cond , read_socket, NULL);
}
|
2,521,869 | 2,521,902 | Constant expression with custom object | I'm trying to use an instant of a custom class as a template parameter.
class X {
public:
X() {};
};
template <class Foo, Foo foo>
struct Bar {
};
const X x;
Bar<X, x> foo;
The compiler states that x cannot appear in a constant expression. Why that? There is everything given to construct that object at compile tim... | You can't do it. Standard 14.1 says:
4 A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
— integral or enumeration type,
— pointer to object or pointer to function,
— reference to object or reference to function,
— pointer to member.
5 [ Note: other types are disall... |
2,522,159 | 2,526,656 | boost smart pointers and BOOST_NO_MEMBER_TEMPLATES | After some struggling I managed to get boost smart pointers to build for Windows CE/Mobile at warning level 4.
I found the least-resistance-way to get rid of compile errors and warnings to be
#define BOOST_NO_MEMBER_TEMPLATES
What does it actually mean? Did I sell my soul to the devil? Will all hell break loose when I... | There shouldn't be any bad effects per se, just a loss of functionality.
A member template is a member function that is a template, for example:
struct foo
{
template <typename T>
void i_am_not_supported_sometimes(void);
};
So you don't get undefined behavior or anything, you just can't program things in a mos... |
2,522,299 | 2,522,311 | C++ catch blocks - catch exception by value or reference? |
Possible Duplicate:
catch exception by pointer in C++
I always catch exceptions by value. e.g
try{
...
}
catch(CustomException e){
...
}
But I came across some code that instead had catch(CustomException &e) instead. Is this a)fine b)wrong c)a grey area?
| The standard practice for exceptions in C++ is ...
Throw by value, catch by reference
Catching by value is problematic in the face of inheritance hierarchies. Suppose for your example that there is another type MyException which inherits from CustomException and overrides items like an error code. If a MyException ... |
2,522,687 | 2,522,710 | Why isn't the reference counter in boost::shared_ptr volatile? | In the boost::shared_ptr destructor, this is done:
if(--*pn == 0)
{
boost::checked_delete(px);
delete pn;
}
where pn is a pointer to the reference counter, which is typedefed as
shared_ptr::count_type -> detail::atomic_count -> long
I would have expected the long to be volatile long, given threaded usage and ... | Because volatile is not necessary for multithreading, and does nothing beneficial, but potentially destroys a number of optimizations.
In order to ensure safe multithreaded access to a variable, the primitive we need is a memory barrier, which provides both the guarantee of volatile and a few others (it prevents memory... |
2,522,688 | 2,577,897 | Hook filtering Keyboards HKEYS issue in c | I am filtering the HKEYS by using Hook filtering function, I use the following code to disable Alt+Tab, Alt+Esc, Ctrl+Esc, Windows Key
if (((lParam.vkCode == 9) && (lParam.flags == 32))||
((lParam.vkCode == 27) && (lParam.flags == 32))||
((lParam.vkCode == 27) && (lParam.flags == 0)) ||
((lParam.vkCode ... | I have got answer of my own question, ctrl+alt+del can't filter out from hook, the only way to disable ctrl+alt+del is to modify the registry form your code..
|
2,522,915 | 2,524,312 | QTableWidget alignement with the borders of its parent QWidget | Let's consider we have QWidget that contains QTableWidget (only). So we want to resize the table by resizing the widget, and we dont want to have an indet between the QWidget border and cells of the table. What kind of property is making posible for QTableWidget to be aligned with the borders of it parent widget?
Thank... | First, you want to make sure the QTableWidget is placed inside a layout. For instance,
QTableWidget* tw = new QTableWidget(parent_widget);
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(tw);
parent_widget->setLayout(layout);
assuming parent_widget is already pointing to the widget containing the QTableWid... |
2,522,934 | 7,292,557 | Enabling Direct3D-specific features (transparency AA) | I am trying to enable transparency antialiasing in my Ogre-Direct3D application, but it just won't work.
HRESULT hres = d3dSystem->getDevice()->SetRenderState(D3DRS_ADAPTIVETESS_Y, (D3DFORMAT)MAKEFOURCC('S', 'S', 'A', 'A'));
/// returned value : hres == S_OK !
This method is taken from NVidia's technical report.
I can... | Next time you have this kind of a problem, be sure to debug what states are currently active et al.
For example you could enable direct3D debug mode and enable state changes logging.
As shown here: http://blog.rthand.com/post/2010/10/25/Capture-DirectX-1011-debug-output-to-Visual-Studio.aspx
Hope that helps,
Cheers,
Ro... |
2,523,025 | 2,523,042 | Unsigned double in C++? | Why doesn't C++ support unsigned double syntax?
| Because typical floating point formats don't support unsigned numbers. See, for instance, this list of IEEE 754 formats.
Adding a numerical format that isn't supported by common hardware just makes life difficult for compiler writers, and is probably not considered worth the effort.
|
2,523,099 | 2,525,450 | Where is cmcfg32.lib? | I found a source code on MSDN about how to enable/disable privileges in C++
According to the source code, the linker must include cmcfg32.lib, but it can't be found...
I tried to compile without including that lib, it compiles without any error, but when I launch my program, it crashes with a fatal error.
So please, if... | It looks (to me) like a minor error in the code. Delete the line:
#pragma comment(lib, "cmcfg32.lib")
Of, if you want the correct library linked automatically, change it to:
#pragma comment(lib, "advapi32.lib")
|
2,523,139 | 2,523,166 | Const references when dereferencing iterator on set, starting from Visual Studio 2010 | Starting from Visual Studio 2010, iterating over a set seems to return an iterator that dereferences the data as 'const data' instead of non-const.
The following code is an example of something that does compile on Visual Studio 2005, but not on 2010 (this is an artificial example, but clearly illustrates the problem w... | The iterator should give you a const reference (and that's what the Standard says it should do), because changing the thing referred to would destroy the validity of the set's underlying data structure - the set doesn't "know" that the field you are changing is not actually part of the key. The alternatives are to make... |
2,523,165 | 2,523,204 | Can't access a map member from a pointer | That's my first question :)
I'm storing the configuration of my program in a Group->Key->Value form, like the old INIs. I'm storing the information in a pair of structures.
First one, I'm using a std::map with string+ptr for the groups info (the group name in the string key). The second std::map value is a pointer to t... | keyValueIt is not a map iterator, it is a list iterator.
You can just do
if (keyValueIt->find(d) != keyValueIt->end())
|
2,523,191 | 2,523,244 | A function's static and dynamic parent | I'm reading Thinking in C++ (vol. 2):
Whenever a function is called,
information about that function is
pushed onto the runtime stack in an
activation record instance (ARI), also
called a stack frame. A typical stack
frame contains (1) the address of the
calling function (so execution can
return to it), ... | This all sounds very odd to me. Static frame pointers are normally used in languages with lexical scope, such as functional languages, and the pascal family with their nested functions. Globals are bound once either at compile time or runtime, and shouldn't need frame pointers. (1) is valid, but (2) doesn't exist in C+... |
2,523,516 | 2,523,538 | Why can I call a non-const member function pointer from a const method? | A co-worker asked about some code like this that originally had templates in it.
I have removed the templates, but the core question remains: why does this compile OK?
#include <iostream>
class X
{
public:
void foo() { std::cout << "Here\n"; }
};
typedef void (X::*XFUNC)() ;
class CX
{
public:
explicit CX(X... | In this context object is a reference to a X, not a reference to a const X. The const qualifier would be applied to the member (i.e. the reference, but references can't be const), not to the referenced object.
If you change your class definition to not using a reference:
// ...
private:
X object;
// ...
you get th... |
2,523,765 | 2,523,786 | QString to char* conversion | I was trying to convert a QString to char* type by the following methods, but they don't seem to work.
//QLineEdit *line=new QLineEdit();{just to describe what is line here}
QString temp=line->text();
char *str=(char *)malloc(10);
QByteArray ba=temp.toLatin1();
strcpy(str,ba.data());
Can you elaborate the possible fl... | Well, the Qt FAQ says:
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QString str1 = "Test";
QByteArray ba = str1.toLocal8Bit();
const char *c_str2 = ba.data();
printf("str2: %s", c_str2);
return app.exec();
}
So perhaps you're having other problems. How exactly doesn't this work?
|
2,523,802 | 2,523,831 | Should a method that waits for a change of state be const? | In a multithreaded scenario, I have a method like this:
bool WaitForChange( time_duration WaitTime ) const;
This method waits either until the state of the object has changed and returns true, or until the timeout times out (how do you say that?) and returns false.
My intuition is, that const is to protect against unw... | By declaring the method as const, you say "Calling this method doesn't change the state of the object." This is (hopefully) true. So make it const.
If anybody thinks, const-ness means "While this method is called, no one else can change the object state" than that person is wrong.
|
2,523,981 | 2,524,024 | Converting a pointer for a base class into an inherited class | I'm working on a small roguelike game, and for any object/"thing" that is not a part of the map is based off an XEntity class. There are several classes that depend on it, such as XPlayer, XItem, and XMonster.
My problem is, that I want to convert a pointer from XEntity to XItem when I know that an object is in item. ... | If you know that the XEntity is actuall and XItem then you can use a static cast.
XItem* Item = static_cast<XItem *>(Ent);
However, you should review you design and see if you can operate on the entity in a way that means that you don't need to know what derived type it is. If you can give the base class a sufficientl... |
2,524,233 | 2,524,322 | Speed accessing a std::vector by iterator vs by operator[]/index? | Say, I have a
std::vector<SomeClass *> v;
in my code and I need to access its elements very often in the program, looping them forward and backward .
Which is the fastest access type between those two ?
Iterator access:
std::vector<SomeClass *> v;
std::vector<SomeClass *>::iterator i;
std::vector<SomeClass *>::revers... | The performance difference is likely negligable or none (the compiler might optimise them to be identical); you should worry about other things, like whether your program is correct (a slow but correct program is better than a fast and incorrect program). There are other advantages to using iterators though, such as b... |
2,524,737 | 2,524,933 | Fixed-size floating point types | In the stdint.h (C99), boost/cstdint.hpp, and cstdint (C++0x) headers there is, among others, the type int32_t.
Are there similar fixed-size floating point types? Something like float32_t?
| Nothing like this exists in the C or C++ standards at present. In fact, there isn't even a guarantee that float will be a binary floating-point format at all.
Some compilers guarantee that the float type will be the IEEE-754 32 bit binary format. Some do not. In reality, float is in fact the IEEE-754 single type on ... |
2,524,816 | 2,524,898 | Creating and Compiling a C++ project on Windows | I need to work on C++ project on my windows machine. My project will consist of various classes(.h and .cpp) as well as the startup file to start the application. The preliminary design is simple but the application has the potential to gain complexity as time goes by. What I need here is ideas to set up the C++ projec... | I've used mingw and netbeans to develop on Windows. I chose Netbeans because it isn't excessively complicated to learn and is cross platform. I didn't like eclipse because it was in my opinion overly complex and the debugger didn't work for me in windows.
|
2,525,035 | 2,526,586 | Is there any lib for crossplatform Camera like devices streams parsing? | C\C++ lib for cross-platform device streams capturing (It shall find all devices in system and be able to give me their streams for encoding or filtering or any thing else). I want it to be cross-platrorm So is there any lib like this, opensource?
| Not sure if it meets your requirements, but what you ask sounds close to GStreamer.
|
2,525,081 | 2,525,102 | Any software to auto generate doxygen comment blocks? | I'm developing a large C++ program and I've now decided to document it with Doxygen.
There are plenty of classes, methods, functions, macros and so on. Therefore I'm searching for software that would scan my source tree and insert Doxygen comment blocks on top of every "documentable item" to let me edit them later and ... | You can set Doxygen to extract non-documented items as well - that may do what you want without adding ANY comment blocks to the code yet.
After that you can create templates / macros (depends on your IDE) to create pre-formatted blocks for each type of item, as you slowly work through the code documenting items one by... |
2,525,087 | 2,525,573 | Is it possible to find the KNN for a node that is *IN* the KD-tree? | Trying to create a KNN search using a KD-tree. I can form the KD-tree fine (or at least, I believe I can!). My problem is that I am searching to find the closest 2 neighbours to every point in a list of points.
So, is there a method to find the K nearest neighbours to a point using a KD tree even if the point is actua... | If you want the K exact nearest-neighbors within your tree, just query the tree for K+1 neighbors (obviously since the first nearest neighbor will be your query).
|
2,525,172 | 2,525,209 | Custom "Very Long Int" Division Issue | So, for a very silly project in C++, we are making our own long integer class, called VLI (Very Long Int). The way it works (they backboned it, blame them for stupidity) is this:
User inputs up to 50 digits, which are input as string.
String is stored in pre-made Sequence class, which stores the string in an array, in... | Implement the long division algorithm you learned in grade school.
Start by implementing subtraction. Create a function which can string-subtract any number from the input. Then you should be able to detect whether the result is negative. Modify this function to allow the number to be string-shifted before you subtract... |
2,525,183 | 2,525,185 | How many arguments does main() have in C/C++ | What numbers of arguments are used for main? What variants of main definition is possible?
| C++ Standard: (Source)
The C++98 standard says in section 3.6.1.2
It shall have a return type of type
int, but otherwise its type is
implementation-defined. All
implementations shall allow both the
following definitions of main: int
main() and int main(int argc, char*
argv[])
Commonly there are 3 sets of ... |
2,525,277 | 2,525,837 | c++ templates: problem with member specialization | I am attempting to create a template "AutoClass" that create an arbitrary class with an arbitrary set of members, such as:
AutoClass<int,int,double,double> a;
a.set(1,1);
a.set(0,2);
a.set(3,99.7);
std::cout << "Hello world! " << a.get(0) << " " << a.get(1) << " " << a.get(3) << std::endl;
By now I have an AutoClass w... | First of all, I prefer Boost.Fusion to Boost.Tuple as it supports a better mixin of template metaprogramming and runtime algorithms I think.
For example, I'd like to present you a little marvel:
struct Name {}; extern const Name name;
struct GivenName {}; extern const GivenName givenName;
struct Age {}; extern const Ag... |
2,525,352 | 2,525,418 | Problem of using cin twice | Here is the code:
string str;
cin>>str;
cout<<"first input:"<<str<<endl;
getline(cin, str);
cout<<"line input:"<<str<<endl;
The result is that getline never pauses for user input, therefore the second output is always empty.
After spending some time on it, I realized after the first call "cin>>str", it seems '\n' is st... | Good writeup that explains some of the reasons why you are running into this issue, primarily due to the behavior of the input types and that you are mixing them
|
2,525,869 | 2,525,931 | Declaring STL Data Structures such as Vector in the .h | I am trying to declare a private Data Structure such as the Vector in my C++ header file which I want to eventually use within the method implementation of my .cpp.
An example would be my header "SomeClass.h" where I have:
class SomeClass
{
private:
Vector<T> myVector;
public:
void AddTtoMyVector(T add);
}
And... | Be sure to specify that you're using STL's vector, using either
std::vector<T> myVector;
or
using std::vector;
Also, if T is a generic type, you want to make the whole class templated:
#include <vector>
using std::vector;
template< typename T >
class SomeClass
{
private:
vector<T> myVector;
public:
void Add... |
2,525,984 | 2,526,093 | Template access of symbol in unnamed namespace | We are upgrading our XL C/C++ compiler from V8.0 to V10.1 and found some code that is now giving us an error, even though it compiled under V8.0. Here's a minimal example:
test.h:
#include <iostream>
#include <string>
template <class T>
void f()
{
std::cout << TEST << std::endl;
}
test.cpp:
#include <string>
#incl... | This is not valid C++ code. TEST is not dependent on the template parameter T, so it must be found in the context of the template definition when it's parsed. However, in that context no declaration of TEST exists, and so there is an error.
The diagnostic message for that ill-formed template can be delayed until insta... |
2,526,044 | 2,526,060 | Why is sizeof giving me this result? | I have this code
struct Student {
char name[48];
float grade;
int marks[10,5];
char gender;
};
Student s;
Now I have to get the sizeof s
so I added
printf("%d",sizeof(s));
now when I hit compile the result showing is 256
and its wrong because it shoud be 253
as because the size of
char name[48]; ----> 48
and
floa... | There may be padding bytes between the members of the struct or at the end of the struct.
In this case, it is likely that there are three bytes of padding at the end of the struct, after the single char member, to ensure that the size of the struct is a multiple of four.
|
2,526,227 | 2,528,383 | C/C++ RPC Tutorial for Linux | Can someone point me to a decent RPC tutorial for (or books) linux, like in this post. I tried looking around myself, I've only found tutorials that are really old.
Thanks
| Since the idea of RPC goes back to 1976 and the first business use was by Xerox in 1981, I'm not exactly sure what qualifies as a really old tutorial.
Here are a few resources you might find helpful.
Power Programming with RPC (1992)
Remote Procedure Calls | Linux Journal (Oct 01, 1997)
Remote Procedure Calls (RPC) (... |
2,526,343 | 2,526,370 | Initializing an array before initializing a pointer to that same array | I want to initialize an array and then initialize a pointer to that array.
int *pointer;
pointer = new int[4] = {3,4,2,6};
delete[] pointer;
pointer = new int[4] = {2,7,3,8};
delete[] pointer;
How can I do this?
| Why not use
int array[4] = {3, 4, 2, 6};
Is there a reason you want to allocate memory for the array from heap?
Suggestion after comment:
int arrays[32][4] = {{3, 4, 2, 6}, {3, 4, 1, 2}, ...}
int *pointers[4];
pointers[0] = arrays[0];
pointers[1] = arrays[12];
pointers[2] = arrays[25];
pointers[3] = arrays[13];
...
p... |
2,526,483 | 2,875,317 | Gamma Distribution in Boost | I'm trying to use the Gamma distribution from boost::math but it looks like it isn't possible to use it with boost::variate_generator. Could someone confirm that? Or is there a way to use it.
I discovered that there is a boost::gamma_distribution undocumented that could probably be used too but it only allows to choose... | As mentioned in this link, you can extend Boost's (or TR1's) one-parameter gamma distribution simply by multiplying the output of the rng by your desired scale.
Below is sample code that uses variate_generator to draw numbers from a gamma distribution, parameterized by mean and variance:
#include <boost/random.hpp>
#in... |
2,526,536 | 2,526,757 | Can anyone explain what features of the C runtime in Android (via NDK) are not supported? | More specifically, does NDK have a complete STL implementation. We're looking at this for devices running 1.6 and upwards.
| No, the only supported libraries in the NDK at this time are:
libc
libm
libz (Zlib compression)
liblog (Android logging)
OpenGL ES 1.1 and OpenGL ES 2.0 (3D graphics libraries)
Also available are interfaces for JNI and minimal C++ support.
|
2,526,711 | 2,526,739 | Class declaration confusion - name between closing brace and semi-colon | class CRectangle {
int x, y;
public:
void set_values (int,int);
int area (void);
} rect;
In this example, what does 'rect' after the closing brace and between the semi-colon mean in this class definition? I'm having trouble finding a clear explanation. Also: Whatever it is, can you do it for structs to... | rect is the name of a variable (an object in this case).
It is exactly as if it had said:
int rect;
except instead of int there is a definition of a new type, called a CRectangle. Usually, class types are declared separately and then used as
CRectangle rect;
as you are probably familiar with, but it's perfectly l... |
2,526,862 | 2,526,883 | Tutorials and Introductions to C++ Expression Templates | What are good introductions to the creation of C++ expression template systems? I would like to express arithmetic on user defined types while avoiding temporary values (which may be large), and to learn how to do this directly rather than applying an existing library.
I have found Todd Veldhuizen's original paper and ... | You should get a copy of C++ Templates: The Complete Guide.
The code example to which you link doesn't have the accompanying text, which is quite helpful (the chapter on expression templates is 22 pages long). Without the text, all you have is code without any comments or explanation as to what it does and how and wh... |
2,526,933 | 2,526,948 | Embed timestamp in object code at compile time with C++ | I want to perform a printf() to display when the currently executing code was last compiled. Does C/C++ provide a macro that gives you that resolves to a timestamp during compilation?
| You could use __DATE__ and __TIME__.
|
2,527,290 | 2,527,319 | Visualizing volume of PCM samples | I have several chunks of PCM audio (G.711) in my C++ application. I would like to visualize the different audio volume in each of these chunks.
My first attempt was to calculate the average of the sample values for each chunk and use that as an a volume indicator, but this doesn't work well. I do get 0 for chunks with ... | Note, I haven't worked with G.711 PCM audio myself, but I presume that you are performing the correct conversion from the encoded amplitude to an actual amplitude before processing the values.
You'd expect the average value of most samples to be approximately zero as sound waveforms oscillate either side of zero.
A cru... |
2,527,437 | 2,527,449 | Adding characters to string | I am currently trying to build a very basic serial shell with my arduino.
I am able to get an output from the device using Serial.read() and can get the character it has outputted, but I cannot work out how to then add that character to a longer to form the full command.
I tried the logical thing but it doesn't work:
c... | Use std::string if you can. If you can't :
snprintf(Command, sizeof(Command), "%s%c", Command, clinput);
or (remeber to check that Command does not grow too much...)
size_t len = strlen(Command);
Command[len] = clinput;
Command[len + 1] = '\0';
|
2,527,697 | 2,528,102 | Problem with extern keyword in C++ | What's the difference between the following two declarations? I thought they were equivalent, but the first sample works, and the second does not. I mean it compiles and runs, but the bitmap display code shows blank. I have not stepped through it yet, but am I missing something obvious? GUI_BITMAP is a simple structure... | Your linker may is silently resolving the duplicate symbols behind your back. You might get static libraries from a vendor and have to link them with your program - what is the solution for the situation where you have two such libraries and they both define a common symbol? The linker will just resolve that, choosin... |
2,527,720 | 2,527,741 | Confused about C++'s std::wstring, UTF-16, UTF-8 and displaying strings in a windows GUI | I'm working on a english only C++ program for Windows where we were told "always use std::wstring", but it seems like nobody on the team really has much of an understanding beyond that.
I already read the question titled "std::wstring VS std::string. It was very helpful, but I still don't quite understand how to apply... | Windows from NT4 onwards is based on Unicode encoded strings, yes. Early versions were based on UCS-2, which is the predecessor of UTF-16, and thus does not support all of the characters that UTF-16 does. Later versions are based on UTF-16. Not all OSes are based on UTF-16/UCS-2, though. *nix systems, for instance, ... |
2,527,739 | 2,527,787 | Newbie questions about COM | I am quite new to COM so the question may seem naive.
Q1. About Windows DLL
Based on my understanding, a Windows DLL can export functions, types(classes) and global variables. Is this understanding all right?
Q2. About COM
My naive understanding is that: a COM DLL seems to be just a new logical way to organize the func... | Think of COM as a binary compatible way to share interfaces across DLL boundaries. C++ classes can't easily be exported from DLLs because of the non-standard name mangling done between various compiler versions. COM allows code in one DLL or executable, to create an implementation of an interface from another DLL or ... |
2,527,778 | 2,529,930 | Insert character infront of each word in a string using C++ | I have a string, for example; "llama,goat,cow" and I just need to put a '@' in front of each word so my string will look like "@llama,@goat,@cow", but I need the values to be dynamic also, and always with a '@' at the beginning.
Not knowing a great deal of C++ could someone please help me find the easiest solution to t... | Judging by insertable's comments, (s?) he's trying to get this code working... So let me offer my take...
As with the others, I'm presuming each word is delimited by a single ",". If you can have multiple character delimiters, you'll need to add a second find (i.e. find_first_not_of) to find the start/end of each wor... |
2,527,780 | 2,527,797 | C++ Linker Error SDL Image - could not read symbols | I'm trying to use the SDL_Image library and I've added the .so to the link libraries list for my project (I'm using Code::Blocks, by the way).
After doing this, when I go to compile, I get this error:
Linking console executable: bin/Debug/ttfx
/usr/lib32/libSDL_image-1.2.so: could not read symbols: File in wrong format... | During the linking step there are incompatibilities since some of your object files were compiled for 32-bit and some for 64-bit. Looking at its path libSDL_image.so was probably compiled for 32-bit.
If you use the GNU compiler add -m32 to your CXXFLAGS to compile your objects for 32-bit, too.
|
2,527,885 | 2,528,056 | Is there anything RAD comparable to VCL? | After years in embedded programming, I have to develop a Windows app. I dug out my old C++ Builder and Delphi. These are great and the latest version costs over $1k, so I won't be going there.
What I particularly like is the VCL (visual component library) which let's me code my own components and share them with others... | Try Lazarus, Lazarus is a cross platform visual IDE for Pascal and Object Pascal developers. It is developed for and supported by the Free Pascal compiler. is available for several Linux distributions, FreeBSD, Microsoft Windows (win32/64/CE) and Mac OS X (including IPhone/IPad). The language syntax has excellent com... |
2,527,951 | 2,527,957 | What does this mean: warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’ | I have a member function in a class that has a callback, but the callback isn't strictly neccessary, so it has a default callback, which is empty. It seems to work fine, but I get an annoying warning:
warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’
I'm trying to figure out what it means and how to tur... | The issue is that you're passing a pointer to an instance method rather than a static method. If you make doNothing a static method (which means no implicit instance argument), the warning goes away.
Specifically,
warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’
exactly is saying that it's converti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.