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 |
|---|---|---|---|---|
5,728,116 | 5,728,158 | Can I link object files made by one compile to those made by another one? | To be more specific, lets assume that both compilers are on the same platform (OS + instruction set). However, one of the object files was made from a compiler-dependent code. On the other hand - the code is object oriented and respects encapsulation.
I need this for a kind of a framework I am making. Target platform i... | You should be able to link them as long as they use the same object file format and target the same machine instruction set. For example, say you have two C compilers each with it's own proprietary language extensions. You compile two different files, one with compiler A the other with compiler B. Each source file ... |
5,728,203 | 6,245,738 | Automatic partial derivation of integrals of polynoms | I've been searching for a C/C++ library that does symbolic differantation and integrals of polynoms, but haven't found one that suits my needs.
I'm afraid that the problem is that I'm not using the correct terminology.
The problem is this :
given a polynom p, I would like to look at the function
f(p) = integral of (p')... | Have you tried to use http://www.fadbad.com/fadbad.html ? It's quite useful.
|
5,728,359 | 5,728,410 | STL internals: deque implementation | I am using a std::deque for storing a large collection of items.
I know that deques is implemented as a list of vectors. The size of those vectors cannot be set but I wander what is the algorithm for choosing that size.
| deque is implemented as a vector of vectors (a list of vectors would impede the constant time random access). The size of the secondary vectors is implementation dependent, a common algorithm is to use a constant size in bytes.
|
5,728,512 | 5,733,666 | Will the pointer to a template member function inside a constructor force instantiation? | Consider the following header file:
// Foo.h
class Foo {
public: template <typename T> void read(T& value);
};
It seems that assigning a pointer to Foo::read<T> in the constructor of a class, of which variable is then declared, cause instantiation:
// Foo.cc
#include "Foo.h"
template <typename T>
void Foo::read(T... | Yes, your solution is portable. Here is a different way
template <typename T, T> struct user { };
template <typename T> struct Bar {
typedef user< void (Foo::*)(T&), &Foo::read<T> > user_type;
};
Now whenever Bar<T> is implicitly instantiated, it will implicitly instanitate Foo::read<T>. No object needs to be crea... |
5,729,061 | 5,730,230 | Loading a class from XML with boost serialization | I'm trying to load a simple class from a XML file but getting the following error:
error: no match for 'operator>>' in 'xml >> boost::serialization::make_nvp(const
char*, T&) [with T = Options](((Options&)(& o)))'
It must be something stupid I'm doing wrong, but I can't figure out what. Does someone have an idea? Here... | Well from your code and what you are writing it would result you are trying to read. In this case you shouldn't use ofstream and xml_oarchive but ifstream and xml_iarchive.
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
....
//for read
std::ifstream ifs("input.xml");
boost::archiv... |
5,729,132 | 5,729,172 | How to add elements to a Boost.Tuple | Maybe this is a simple question, but I can't figure it out how can I add elements to a tuple. What I want is to iterate a vector and add every element into a tuple:
for(it = vector.begin(); it != vector.end(); ++it)
{
tuple.addElement(*it);
}
I dont see any specific method to add elements.
Thanks for helping.
| You don't "add elements" to a tuple. A tuple is not a container.
Sounds like perhaps you're looking for a std::vector, or perhaps some other container.
|
5,729,230 | 5,729,681 | Installable Linux daemons, how to create them in C++? | Installable Linux daemons, how to create them in C++ ?
I have a server applicationin C++ which I want it to behave the same way as a Windows Service. Ie it should be started whenever the system is started independently of whether there is a user logged in or not. In Windows there are a lot of C++ classes able to facili... | Ok, the first thing, you need to know that writing services in Windows and Linux is very different. First of all, in Linux, "services" are not called "services", they're called "daemons". Knowing that, you can use google to find this extremely useful document.
As for starting/stopping/restarting, there is no universal... |
5,729,336 | 5,729,362 | function returning this pointer in c++ | 1st code:
#include <iostream>
using namespace std;
class demo
{
int a;
public:
demo():a(9){}
demo& fun()//return type isdemo&
{
return *this;
}
};
int main()
{
demo obj;
obj.fun();
return 0;
}
2nd code:
#include <iostream>
using namespace std;
class demo
{
int a;
public:
demo():a(9){}
demo f... | demo & fun() returns a reference to the current object. demo fun() returns a new object, made by copying the current object.
|
5,729,808 | 5,729,900 | How do I invoke the shell "file copy dialog" to report the progress of a copy in Win32? | How can I copy files by invoking windows "copy files" dialog to do it?
SHFileOperation seems like a option, but it is inside our process.
By the way, does SHFileOperation have GUI interface? Is it exactly the same as the Windows copy dialog?
| Yes, this is what the SHFileOperation function is designed for. It accepts an SHFILEOPSTRUCT structure as its only parameter, which you can use to specify the options that you want.
However, it has been replaced in Windows Vista and later versions with the IFileOperation interface.
|
5,729,863 | 5,729,950 | Problems with map as array | Good day!
I'm making nondeterministic finite automata with c++. I want to make a transition table. As you know, it should return a set of states. For example, table[state][symbol] should return {q0,q1, etc..}.
I'm using std::map and std::set for this. I found this useful example : how to use stl::map as two dimension a... | From your description it sounds like you want (typedefs for readability):
typedef std::set<state> StateSet;
typedef std::map<char, StateSet> SymbolToStatesMap;
typedef std::map<state, SymbolToStatesMap> TransitionTable;
TransitionTable transitionTable;
Keep in mind that the first type argument to map is the key type,... |
5,729,964 | 5,734,019 | Why ARM NEON not faster than plain C++? | Here is a C++ code:
#define ARR_SIZE_TEST ( 8 * 1024 * 1024 )
void cpp_tst_add( unsigned* x, unsigned* y )
{
for ( register int i = 0; i < ARR_SIZE_TEST; ++i )
{
x[ i ] = x[ i ] + y[ i ];
}
}
Here is a neon version:
void neon_assm_tst_add( unsigned* x, unsigned* y )
{
register unsigned i = ARR... | The NEON pipeline on Cortex-A8 is in-order executing, and has limited hit-under-miss (no renaming), so you're limited by memory latency (as you're using more than L1/L2 cache size). Your code has immediate dependencies on the values loaded from memory, so it'll stall constantly waiting for memory. This would explain wh... |
5,730,279 | 5,730,473 | Is there a standard 3d vector class in C++ | In an existing project, I see a class Vector_3d, templated, with the usual operations for vectors (in the sense of algebra). After profiling, I noticed that a large amount of the time is spent in this class.
I was wondering if there was a well-known implementation of such a basic concept as a 3d vector in C++. Indeed,... | There is no much room for improvement in a 3d vector class (basically, dot / cross products are fairly easy, matrix multiplication as well).
If so much time is spent in that class, maybe your code using it is flawed. Have you checked against
copy vs references
wrong association (like multiply matrix then all vectors ... |
5,730,319 | 5,730,417 | How compiler make's sure that no data member state is changed in the const member function? (either in C++ or java) | How can a C++ or Java compiler make sure that none of the member variables state is changed in a const member function (mutable is exceptional).
Will the compiler do something like putting the code in a non-writable code segment or something like that?
| The compiler doesn't make sure. It can't, since there's no rule
in the language that says that member variable state cannot
change in a const member function. The only rule is that you
cannot change the state through the this pointer (without
casting away const).
|
5,730,747 | 5,730,907 | How to pass an argument to boost::thread? | thread_ = boost::thread( boost::function< void (void)>( boost::bind( &clientTCP::run , this ) ) );
is it possible that run has an argument like this :
void clientTCP::run(boost:function<void(std::string)> func);
and if yes how my boost::thread call should be written
Thanks.
| The following code boost::bind( &clientTCP::run , this ) defines a function callback. It calls the function run on the current instance (this). With boost::bind you can do the following:
// Pass pMyParameter through to the run() function
boost::bind(&clientTCP::run, this, pMyParameter)
See the documentation and exampl... |
5,730,968 | 5,731,085 | How to sum two spars matrix together in c++? | I want to add two sparse matrices together in C++?
| If you use the boost::ublas library, then you can simply add them together, something like this.
#include <boost/numeric/ublas/matrix_sparse.hpp>
using namespace boost::numeric::ublas;
compressed_matrix<double > A(30000, 100, 30000 ),B(30000, 100, 30000 ),C(30000, 100, 30000 );
A(1,1) = 1.0;
B(99,99) = 10.0;
C = A + B;... |
5,731,035 | 5,731,118 | How to implement grep in C++ so it works with pipes (stdin,etc.)? | I want to implement grep for a Shell I'm doing in Windows (just for learning purpose).
I know that grep has the following syntax:
grep pattern files
So I can make a function like:
int grep(string stringToMatch, string fileName) // just one file
{
// search file for stringToMatch
// print line containing stringTo... | You want to see how many command line arguments you've been passed. If there is only one then you assume that you're using stdin instead of a file.
In C++ this can be abstracted by using a reference to a std::istream in your function. Before you call the function you decide (and create) a std::ifstream if appropriate, ... |
5,731,133 | 5,742,718 | Support for const_string in std::ostream operator << | I'm currently using the very clever package boost::const_string until http://libcxx.llvm.org/ is available pre-packaged on Ubuntu or GCC make its __versa_string (in header ext/vstring.h) its default string implementation. libcxx's std::string aswell as __versa_string uses _small-string optimization (SSO) by default. De... |
Have I missed something?
Yes, just include const_string/io.hpp. All it does however is:
return o << std::basic_string<char_type, traits_type>(s.data(), s.size());
|
5,731,217 | 5,731,259 | How to copy/create derived class instance from a pointer to a polymorphic base class? | I have been struggling with this kind of problem for a long time, so I decided to ask here.
class Base {
virtual ~Base();
};
class Derived1 : public Base { ... };
class Derived2 : public Base { ... };
...
// Copies the instance of derived class pointed by the *base pointer
Base* CreateCopy(Base* base);
The method s... | You add a virtual Base* clone() const = 0; in your base class and implement it appropriately in your Derived classes. If your Base is not abstract, you can of course call its copy-constructor, but that's a bit dangerous: If you forget to implement it in a derived class, you'll get (probably unwanted) slicing.
If you do... |
5,731,278 | 5,731,436 | alternative to union for classes with ctors | I have a design-related question in C++.
I'm building a tree for a HW assignment.
The tree implementation is pretty straightforward. Basically it's a templated class
template <typename TYPE, typename KEY>
class Tree
{
public:
void Insert(TYPE& node);
void Remove(TYPE& node);
TYPE& Find (KEY key);
//etc.
};
So far ... | The actual problem in your code is that you try to place the comparision and the employee data structure to the same object. They should be different objects like this:
template<class T> class ICompare {
virtual bool Compare(const T &a, const T &b) const=0;
};
and then obviously you need to modify the Tree construct... |
5,731,396 | 5,732,827 | Internet Explorer BHO check for multi-instance of site | I'm working on a project for a client. We are building an internal web portal, and for various (mostly political) reasons have ended up building a BHO for IE8. One of the things t does is make sur that only one instance of the portal can be opened at once. It does this by writing a temp file when the portal is opened. ... | If you want limit browser instances in the current user session you can use a mutex instead of a file. try acquire the mutex at the startup of the BHO (in the SetSite call) with a reasonable timeout, and release again in the final SetSite call.
If the result is WAIT_OBJECT_0 or WAIT_ABANDONED, there is no other BHO ins... |
5,731,459 | 5,732,927 | Reading binary files | I've to read data from binary file.
This binary data format is:
0x00 0x00 0x01 - is delimiter
after this delimiter there is raw data byte array.
So, to sum up, my binary file looks like:
0x00 0x00 0x01 (here is raw data byte)
0x00 0x00 0x01 (here is another block
of raw data bytes) 0x00 0x00 0x01 ....
So i've wro... | I think the problem there is that putback fails. As far as i recall, putback is guaranteed to work only once; second invocation will fail if the internal read buffer is aligned (that is, very rarely; seems like your situation).
To fix, get rid of putback. First of all, move the loop commented as "finding first delimite... |
5,732,562 | 5,732,680 | Improving g++ output | g++ sometimes produces pretty convoluted outputs. Specially when dealing with templates. Is there any tool that makes g++ output more readable? ... at least some color?
It may sound silly to ask this question here, but I've been unable to google my way out of this.
| If you're free to switch compiler, try clang++. It's error outputs are most of the time very clear and sometimes it will even tell you what to do to fix your error. You can find a comparison of gcc vs clang error output here: http://clang.llvm.org/diagnostics.html.
Otherwise, as noted by Matteo Italia, look to STLFilt.... |
5,732,603 | 5,733,596 | How to compile Boost.Process library? | So there is Boost.Process 2006, Boost.Process 2008 and most recent Boost.Process seems like 2009 by looking at sources) I need some kind of step by step guidance on how to compile that beast. Because I deffenetly do not get how to do such thing.
So For generall official Boost I understand what shall be done
With out a... | I did this once or twice and here's what I remember:
After downloading boost libs e.g. from the sandbox, unpack the lib onto the drive like you said e.g to folder C. If you open the C folder, it generally has the same folder structure as the rest of the boost source. At least this was the case in the limited libraries ... |
5,732,798 | 5,732,852 | c++ array assignment of multiple values | so when you initialize an array, you can assign multiple values to it in one spot:
int array [] = {1,3,34,5,6}
but what if the array is already initialized and I want to completely replace the values of the elements in that array in one line
so
int array [] = {1,3,34,5,6}
array [] = {34,2,4,5,6}
doesn't seem to work... | There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
H... |
5,732,820 | 5,732,893 | Initializing member class with non-default constructor | I'm trying to make a gui which has a SimpleWindow class that contains a textPanel class:
class textPanel{
private:
std::string text_m;
public:
textPanel(std::string str):text_m(str){}
~textPanel();
};
class SimpleWindow{
public:
SimpleWindow();
~SimpleWindow();
... | You want an unnamed temporary value in the initializer list. One simple change will do it:
SimpleWindow::SimpleWindow():
text_panel_m(std::string("default value"))
|
5,732,880 | 5,732,959 | C++ dependency injection - by reference or by boost::shared_ptr? | In cases where constructor dependency injection is required, what are the considerations for using injection by reference vs. using boost::shared_ptr?
Is there another common way of doing it? How does it compare to the two methods above?
| It's your choice on how you want to manage the lifetime of the object you're injecting. The overall architecture will probably dictate which choice makes the most sense. With a reference, something at a higher level must manage the object lifetime; with shared_ptr the lifetime will be managed automatically.
|
5,732,885 | 5,738,091 | How to add new functions to a COM .dll created by a Visual Studio C++ ATL Project | I'm trying to create a very basic COM dll for inclusion in a C# project, to then use to wrap up some C++ functionality into a COM module for inclusion in a C# project (the language used by the rest of the code base).
I included the COM dll, added a class to the COM dll and instantiated it in the C# code, but so far I h... |
I tried adding a class method to MyCOMObject.h
That's not good enough. The super important file in your project is the .idl file (Interface Description Language). That file generates the type library that gets embedded in the DLL. The type library is what .NET uses to generate the managed import library. Your add... |
5,732,902 | 5,733,020 | Convert char array to Unicode | I am developing a device driver in Visual C++.
I need to convert a character array to Unicode as well as
wide character array in my driver.
Pointer to useful functions will be appreciated.
I know "RtlInitUnicodeString" which concerts wchar to Unicode
but need help for conversion of simple character arrays.
| If you are ok with the "current system locale" setting for the input encoding and the output in the usual UTF-16, the RtlAnsiStringToUnicodeString should be available in kernel-mode.
|
5,733,050 | 5,733,066 | c++ class array initialization | so I have this class in the header
class C{
int b [2];
init();
}
and in C.cpp I have
C::init(){
bK [2] = {3,7};
}
whereby I try to initialize the class variable b which is an array
but then the compiler returns the error expected ; before { token and expected primary expression before { token
what did i... | End your class definition with a ;.
class C {
int b [2];
init();
};
Also, you cannot initialize an array like that away from the declaration in standard C++.
|
5,733,061 | 5,733,117 | error C2893: Failed to specialize function template | I am getting this error and another error too ** "IntelliSense: no instance of function template matches the argument list"** when compiling the following code
I know there might be logic mistakes in my function but I need to solve this error first to be able to debug my function .
#include <iostream>
using namespace... | The argument for parameter arr is of type int[5]. Since you didn't specify a template argument for T when calling myMax, argument deduction happens and T is deduced to be int[5].
Then the compiler attempts to specialize the function template with T = int[5] (i.e., it tries to replace all instances of T with int[5]). ... |
5,733,180 | 5,733,237 | Does this run into undefined behavior regarding object lifetimes? | #include "stdio.h"
class C {
public:
~C() { printf("~C\n"); }
};
int I(const C& c) { printf("I\n"); return 0; }
void V(int i) { printf("V\n"); }
int main() {
V(I(C()));
return 0;
}
Seen output:
I
V
~C
what I would have expected:
I
~C
V
| V(I(C()));
C() creates a temporary which persists till the completion of the full expression, and the completion of the full expression is ; (i.e the semicolon). That is why you see that output which is in my opinion is well-defined.
Section §12.2/3 from the Standard reads,
[...] Temporary objects are destroyed as th... |
5,733,202 | 5,733,281 | How to pass user data to compare function of std::sort? | Like qsort(), it seems that C++ std::sort() does not allow to pass user data to the sort function.
For example:
An array of structure like struct A { int version; int index; } array[100] has to be sorted in order, but using this array struct B { int value; } key[100] as the sort key. struct A::index indexes array key.... | Functors don't have to be functions; they can be objects.
struct Comparator {
Comparator(int* key) : key(key) {};
bool operator()(struct A *a1, struct A *a2) {
return key[a1->index].value < key[a2->index].value;
}
int* key;
};
/* ... */
std::sort(container.begin(), container.end(), Comparator(<poin... |
5,733,220 | 5,733,462 | How do I add the MinGW bin directory to my system path? | I am using Windows XP. I am trying to add a new library to Dev-C++. For that, I need to install MinGW and then I have been instructed to add the bin directory of MinGW to my system path. But, I don’t know how to do it. Please guide me (step by step) to add this to my system path.
| To change the path on Windows XP, follow these instructions, and then add the directory where you install MinGW plus bin. Example: if you install MinGW in C:\ then you have to add C:\mingw\bin to your path
Just for completeness here are the steps shown on the link:
From the desktop, right-click My Computer and click P... |
5,733,248 | 5,803,677 | Which file would tell me the mappings in doxygen | I have a doxygen generated html files. I would like to know the mappings between the original C/Java file to its html counterpart.
I was able to do it with some dirty tweaking of file.text in latex folder. Any other approach?
| You can use the GENERATE_TAGFILE feature to let doxygen create a so-called tag file. That's just an XML file which contains the mappings. I didn't find a formal description of the XML dialect, but it seems easy enough. Here's one for libstdc++: http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/libstdc++.tag
|
5,733,254 | 5,733,353 | How can I create my own comparator for a map? | typedef map<string, string> myMap;
When inserting a new pair to myMap, it will use the key string to compare by its own string comparator. Is it possible to override that comparator? For example, I'd like to compare the key string by its length, not by the alphabet. Or is there any other way to sort the map?
| std::map takes up to four template type arguments, the third one being a comparator. E.g.:
struct cmpByStringLength {
bool operator()(const std::string& a, const std::string& b) const {
return a.length() < b.length();
}
};
// ...
std::map<std::string, std::string, cmpByStringLength> myMap;
Alternative... |
5,733,774 | 5,733,832 | C++ - how eliminate macros? (to port app into i.e. c#) | I've created simple virtual machine, and for creating instructions bytes and switch I use c++ macros, it looks like this (thats simplified example):
typedef t_sint_b32 int;
typedef t_sint_b16 short;
(...)
typedef t_sfloat_b32 float;
enum InstructionOpSize{b8,b16,b32,b64};
enum InstructionOpSign{s, u};
enum Instructi... | One option is to move to an external macro processor (e.g. M4) and then make it part of your build process to produce the macro-expanded version before it is compiled. Basically you just move from the C preprocessor to an external preprocessor (e.g. M4).
Another alternative is to restructure the code by hand :)
|
5,733,889 | 5,733,979 | dllexported appended string is corrupt | i have an exe loading a dll. i wrote both.
i am dllexporting a function foo that returns a std::wstring.
all it does is say
std::wstring blah = L"rgjwgfw";
return blah.append(L"hey");
in the exe where i import foo, the string is corrupt. as soon as i return from the function where i call foo i get failed assert... | This is pretty common problem. You need to link both the DLL and the executable to use the standard library in a DLL. That way they share a common copy of the standard library a common heap. Otherwise, you end up with code in the executable trying to use one heap, and code in the DLL using a separate heap. When you pas... |
5,733,944 | 5,734,131 | Qt vs native when writing a background application | I'm about to write a piece of software for my MSc project in C++ and I wish to use this as an opportunity to learn either the Linux native API or the Qt API, both of which are of interest to me, but I'm not sure which one would be more appropriate. I'm sorry if this question seems long, convoluted and somewhat ambiguou... | I vote Qt. The Qt code base is nicely factored to separate the "QtCore" library from the "QtGui" libary. The "QtCore" includes support for processes/threads, signals/slots, and state like that which would be used "independent" of GUI components. (For example, the "QSlider" widget is merely a GUI component that prese... |
5,734,066 | 5,734,156 | How reliable is windows task manager for determining memory usage of programs? | Can I use task manager to detect huge memory leaks? I have a small text parsing program that shows memory usage of around 640K when I launch it. When I parse a file and index it the memory usage grows depending on the size of the file. Then when I "clear" the index, my memory usage drops down to around 1400K. After... | TaskMgr is an extremely crude tool, but it is useful nonetheless. If you have memory leaks in the one megabyte range, then it is probably good enough to tell that you have them. But, eventually, you'll be looking for leaks in the 10 kilobyte and under ranges, and TaskMgr is useless for those.
|
5,734,160 | 5,734,281 | Rationale for throwing static type? | According to the C++ FAQ, when one throws an object, it's thrown using the static type of the expression. Hence, if you have:
catch ( some_exception const &e ) {
// ...
throw e; // throws static type, possibly causing "slicing"; should just "throw;" instead
}
and e is actually a reference to some class derived fr... | The "argument" to throw is an expression and it is the type of the expression that determines the type of the exception object thrown. The type of the expression thrown doesn't necessarily have to be a polymorphic type so there may not be a way to determine if the expression actually refers to a base class subobject of... |
5,734,209 | 5,735,112 | Adding a label to a widget | I am trying to add a label to the main window using Qt. Here is a piece of the code:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget Main_Window;
QPixmap Image;
Image.load("1837.jpg");
QLabel i_label;
i_label.setPixmap(Image);
i_label.show();
QPushButton Bu_Qu... | hamza, this code worked fine for me:
#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget Main_Window;
QLabel i_label("Start", &Main_Window);
//i_label.setPixmap(QPixmap("1837.jpg"));
QPushButton Bu_Quit("Quit" , &Main_Window);
QObject::connect(&Bu_Quit ,... |
5,734,304 | 5,734,491 | c++ boost split string | I'm using the boost::split method to split a string as this:
I first make sure to include the correct header to have access to boost::split:
#include <boost/algorithm/string.hpp>
then:
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
and the line is like
"test test2 test3"
This is how I consu... | The problem is somewhere else in your code, because this works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (size_t i = 0; i < strs.size(); i++)
cout << strs[i] << endl;
and testing your ap... |
5,734,756 | 27,768,381 | Templates and argument dependent lookup | When compiling this program, I was expecting the operator<< call to resolve to the one in the global namespace, but instead, the compiler reports an ambiguous overload. I thought non-dependent lookup occurred before the functions in namespaces that are included as potential matches due to argument dependent lookup. T... | Even though this is an old question, I think there are still some things that haven't been clarified regarding the OP's specific questions, so here we go.
First of all: argument-dependent lookup and normal unqualified lookup are both done for unqualified function and operator calls. This applies to both normal function... |
5,734,768 | 5,734,790 | Function Template: typename declaration | On GCC, The following gives me an error: no type named 'x' in 'struct Type'
On VC++, It complains about p being undeclared
struct Type
{
static int const x = 0;
};
template <class T> void Func()
{
typename T::x * p; // p to be pointer
}
int main()
{
Func<Type>();
}
| T::x becomes Type::x, which is an int, not a type.
You've told the compiler that T::x names a type by using typename. When Func<Type> is instantiated, T::x is not a type, so the compiler reports an error.
|
5,734,794 | 5,734,901 | mouse movement opengl | I am creating a pool game written in C++ using plain OpenGL (no external tools), but I can use GLUT. I have drawn a pool cue which I want to follow the mouse cursor but I am not sure how to do this.
I know how to use keyboard input to move things e.g camera position or draw an object but I
m not sure how to move an ob... | Glut has a few mouse callback function
Mouse callback
Motion callback
You could use the callback to figure out the movement of the mouse, the rest is pure math.
|
5,734,881 | 5,735,133 | Loading an image using DevIL and OpenGL in C++ | As the title suggests, I am trying to load an image using DevIL, before passing it to OpenGL. I am using this piece of code as error control
const char* filename = "back.bmp";
if (!ilLoadImage(filename))
{
throw runtime_error(std::string("Unable to load image") +filename);
}
which, for the if statement, returns t... | If you use Unicode functions, you have to use Unicode text. Specifically, L will return the wide char representation of static text:
ilLoadImage(L"back.bmp");
If you're compiling code for both ANSI and wide strings, use _T() instead, which returns the correct type of string:
ilLoadImage(_T("back.bmp"));
If you're in ... |
5,735,239 | 5,735,283 | Data delimited by space key | I've been assigned a problem I simply do not understand. I know that I need to use a cin function (like cin.get()), but I'm not sure which one I need or how to use it in this circumstance.
I need to create an insertion and extraction operator that reads (and writes) 3 pieces of data. All of the data is of the type in... | With cin, you can just read data using something like this:
int wholepart,numer,denom;
cin>>wholepart>>numer>>denom;
This would read 3 integers into wholepart, numer and denom respectively. It will skip over whitespace separating the integers.
|
5,735,287 | 5,735,352 | How to avoid operator's or method's code duplication for const and non-const objects? |
Possible Duplicate:
How do I remove code duplication between similar const and non-const member functions?
My task is to implement c++ vector analogue. I've coded operator[] for 2 cases.
T myvector::operator[](size_t index) const {//case 1, for indexing const vector
return this->a[index];
}
T & myvector::ope... | One of the few good uses of const_cast here. Write your non const function as normal, then write your const function like so:
const T & myvector::operator[](size_t index) const {
myvector<T> * non_const = const_cast<myvector<T> *>(this);
return (*non_const)[index];
}
|
5,735,349 | 5,912,034 | Where is boost::asio::windows::stream_handle in boost 1.46.1? | Once uppon a time we had boost code like:
typedef BoostAsioPipe pipe;
#elif defined(BOOST_POSIX_API)
typedef boost::asio::posix::stream_descriptor pipe;
#elif defined(BOOST_WINDOWS_API)
typedef boost::asio::windows::stream_handle pipe;
#else
# error "Unsupported platform."
#endif
but now, for example on windows comp... | Is this what you want? (from http://think-async.com/Asio/asio-1.4.8/doc/asio/overview/windows/stream_handle.html)
Windows random-access HANDLEs are only available at compile time when targeting Windows and only when the I/O completion port backend is used (which is the default). A program may test for the macro BOOST_A... |
5,735,411 | 5,736,765 | STL iterators and templates | It's possible to do that without copy containers' data?:
template<typename T> //we know only the type return by iterator
class Foo {
private:
I b; //or some base class of iterator or own generic iterator
I e; //what should be 'I'?
public:
template<typename I>
Foo(begin, end) {
b = begin;
... | If you really want to be able to declare the template dependent only in the type of the data contained in the container, and at the same time you want to be able to store any type of iterator (i.e. iterator into any type of container), the solution is performing type erasure on the iterators.
If you can bring some exte... |
5,735,412 | 5,735,552 | Hiding member functions in a template class | Is it possible to hide some member functions in a template class?
Let's imagine we have something like:
template <class T>
class Increment
{
public:
void init(T initValue)
{
mValue = initValue;
}
T increment()
{
++mValue;
}
T increment(T delta)
{
mValue += de... | In this case, I would prefer using template specialization. Would something like this help you?
struct SingleIncrement;
struct MultipleIncrement;
template <
class T,
class Policy = SingleIncrement // default template param
>
class Increment
{
T mValue;
public:
Increment(T initValue)
: mValue(ini... |
5,735,532 | 5,735,596 | glibc detected, but I'm not using dynamic memory? | Hey, everyone. I'm writing a hexadecimal calculator in C++. The operations have to be done "by hand" because the requirement is for the program to be able to handle 40 digit operands (and 16^40 is much larger than a long long can handle).
I am having a bit of a problem, though. On my Mac (OS X 10.6) I can compile and ... | string str;
char chr[1];
...
sprintf(chr, "%u", sum);
You're overflowing chr, this most likely affects str by overwriting some internal pointer variable used by std::string. When the string is destructed, it tries to delete this invalid pointer.
Make sure chr is large enough - e.g. char chr[32]; should be plenty for p... |
5,735,753 | 5,737,898 | Win API wrapper classes for handles | Writing a wrapper class for a handle that only gets passed by value is relatively easy. I am trying to determine what the best way is to encapsulate handles that need to be passed by address.
For example, writing a wrapper for something like SC_HANDLE that gets passed by value to QueryServiceConfig() is not that diffic... | You can always add another layer of indirection to avoid the awful overloading of operator& and ugly Attach or Detach and return a pre-wrapped instance from there.
If you can use C++0x in VS2010 or gcc, or have other ways of accessing std::unique_ptr<>, then you can do this (error checking omitted for brevity):
struct ... |
5,735,808 | 5,735,914 | How to construct a parser for an input file | can i please get some guidance to constructing a parser for an input file, I've been looking for a help for weeks, the assignment is already past due, I would just like to know how to do it.
The commented code is what I've tried, but i have a feeling it is more serious than that. I have a text file and I want to parse... | To read a word:
std::ifstream file("FileName");
std::string word;
file >> word; // reads one word from a file.
// Testing a word:
if (word == "Floccinaucinihilipilification")
{
++count;
}
// Count multiple words
std::map<std::string, int> count;
// read a word
++count[word];
// To read many words from a f... |
5,736,023 | 5,744,646 | Template export troubles | I can't understand the right way for exporting some function into python with boost.python.
I have exported this class CL_Rectf. It inherits CL_Rectx<float>.
Now I want to export function bounding_rect:
# In CL_Rectf class exporting
.def("BoundingRect", &CL_Rectf::bounding_rect, PYPOLICY_REFERENCE_EXISTING)
It compile... | Without knowing Boost.Python in particular, it seems to me that you exported CL_Rectf, but not CL_Rectx<float>. So when asked to convert a python object into a CL_Rectx<float>, Boost.Python doesn't know how, and raises the exception you see.
My advice would be be to forget about CL_Floatf and export the CL_Rectx<float>... |
5,736,148 | 5,736,404 | Turn .txt file into .pdf file on the fly? | I'm we're trying to figure out if there would be a way to convert a .txt file to a .pdf file. Here's the catch. This needs to be done behind the scenes, and on the fly. Meaning, with a radio control selected, OnOK would create a .txt file. Behind the scenes, at run time, we would like for the .txt file to be conver... | This a2pdf tool will probably do the trick with minimal effort. Just be sure to turn off perl syntax highlighting.
http://perl.jonallen.info/projects/a2pdf
|
5,736,289 | 5,736,352 | Binary compatibility of STL containers | Let's say I write a DLL in C++ and would like to export a method which takes a std::vector parameter. Can I hope for any binary compatibility between different STL versions?
| If you mean between the versions included with updated versions of the same compiler, yes, it can (and will) work in some cases, but you have to be careful. There are also a few special cases, such as the Intel and Microsoft compilers on Windows -- Intel is pretty careful to maintain binary compatibility, and at least ... |
5,736,334 | 5,736,560 | stl vector::insert difference in Windows and linux? | there. I've searched my question around here but failed to find anything relevant.
This is the problem.
I have this code in the part of my program, doing kind of stupid sort by inserts.
I developed that in MSVS 2008 and it all worked fine, but when I tried to compile that with g++, it failed because of list::insert fun... | The signature of the insert member function that you are trying to use is probably:
iterator insert( iterator, const value_type& );
But the first argument that you are passing to the function is a const_iterator, that cannot be implicitly converted to a non const iterator. That code should not have worked on VS either... |
5,736,385 | 5,736,444 | Why does C++ have both classes and structs? |
Possible Duplicate:
What are the differences between struct and class in C++
If the only difference between structs and classes is the default access specifier(in C++), then why does C++ also have classes?
| First, it's backward compatibility with C.
Second (and more importantly), it helps describe your intent. The standard convention is that PODs should be denoted with struct and collections of data and behavior should be denoted with class.
|
5,736,627 | 5,736,712 | Framework for both: web & standalone application | Dear everyone, I am just curious, is it possible to create standalone GUI application which further can be easily migrated to the web? Or, even better, will be able to work in two modes locally and remotely through web browser. Since the main application logic is already written on C++ I read a little about Qt Quick. A... | Depends on what your application does. If it is heavy UI bound and not calculation intense you will not get very far with Qt. There are a few toolkits for Java like GWT which help you to program an AJAX app like you would program a normal desktop GUI - but i don't know any C++ framework doing the same.
For a non heavy... |
5,736,649 | 5,736,834 | Static variables in the scope of a draw function in OpenGL? | As an example, I have the following draw function in some OpenGL application:
void Terrain::Draw(float ox, float oy, float oz) {
float terrainWidth = stepWidth * (width - 1.0f);
float terrainLength = stepLength * (length - 1.0f);
float startWidth = (terrainWidth / 2.0f) - terrainWidth;
float startLength... |
Would I gain anything in declaring those function variables as static?
it's really a small amount of data: don't bother, unless you have a ton of instances.
To prevent them from being destroyed and declared every time the function is called?
this typically takes the form:
class Terrain {
public:
// interface
p... |
5,736,745 | 5,737,017 | Which Data Structure used to solve a simple math equation | When taking in a expression like (10+5*15) and following orders of operations.
How would one best solve a problem like this? What kind of data structure is best?
Thanks.
| I'd go with Dijkstra's Shunting yard algorithm to create the AST.
|
5,736,790 | 5,736,822 | Detect ICC vs GCC at compile time | How to detect at compile time if I'm using gcc or icc?
(I was quite puzzled to find out that icc defines __GNUC__ -- and even __GNUC_MINOR__ and __GNUC_PATCHLEVEL__ ! why?)
| We use
#ifdef __INTEL_COMPILER
to split icc off, assuming gcc as a default.
|
5,736,813 | 5,736,937 | C++ Assertion Failed on vector at runtime Expression: vector subscript out of range | im gettin this really annoying error message. I know Im only new to this but it seems the type of thing I could figure out. Can anyone show me where im going wrong please?
The message at run time is:
Debug Assertion Failed!
Program:
....
File: c:\program files\microsoft visual studio 10.0\vc\include\vector
Line: 932
Ex... | We don't have enough information to say for sure, but I suspect the failing line is r >> numberVector[i]. I suppose you meant to say int j; r >> j; numberVector.push_back(j);
The problem is precisely what the error message says: your vector subscript (i) is out of range. Specifically, you never increase the size of you... |
5,736,915 | 5,736,948 | Is there non-english syntax of c++ | I heard that there is a non-english syntax of c++, it seems to be as c++ style but with translated terms!
can we find a lang like this!
| #define пока while
#define типа virtual
#define дай new
#define нах delete
...
#define бюст boost
|
5,736,968 | 5,737,031 | Why is CUDA pinned memory so fast? | I observe substantial speedups in data transfer when I use pinned memory for CUDA data transfers. On linux, the underlying system call for achieving this is mlock. From the man page of mlock, it states that locking the page prevents it from being swapped out:
mlock() locks pages in the address range starting at addr a... | CUDA Driver checks, if the memory range is locked or not and then it will use a different codepath. Locked memory is stored in the physical memory (RAM), so device can fetch it w/o help from CPU (DMA, aka Async copy; device only need list of physical pages). Not-locked memory can generate a page fault on access, and it... |
5,737,134 | 5,737,692 | BadImageFormatException | i was working with invoking C++ Dlls into C# and ran into a problem
C++ function:
int _declspec(dllexport) CompressPacket(unsigned char *buff, int offset, int len);
C# function:
[DllImport("HuffCompress.dll")]
private static extern unsafe int HuffCompress(ref byte[] buff, int offset, int len);
... | The missing Platform Target setting in the Express edition is almost certainly your problem. You'll have to edit your project's .csproj file by hand. Run notepad.exe and open the .csproj file. Locate the property group that looks like this:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU... |
5,737,222 | 5,737,441 | Garbage from a simple read | int test = 0;
ifstream inFile;
inFile.open("hat.txt");
inFile >> test;
cout << test;
I have the file in the debug folder where the .exe is running and the file of that file is hat.txt. All it has is one number. My question is why am I getting junk when I output ?
EDIT - Added the fail line and it does fail. Why is it... | Your code looks fine now that it has the failed check.
Why did it fail? probably the file doesn't exist or has the wrong permissions.
I ran this code.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int test;
std::ifstream inFile;
inFile.open("hat.txt");
if ( inFile.fail() )
... |
5,737,344 | 5,738,131 | Thread safe memory pool | My application currently is highly performance critical and is requests 3-5 million objects per frame. Initially, to get the ball rolling, I new'd everything and got the application to work and test my algorithms. The application is multi-threaded.
Once I was happy with the performance, I started to create a memory ma... | As said in comments, don't get a thread-safe memory allocator, allocate memory per-thread.
As you implied in your update, you need to manage free/in-use effectively. That is a pretty straightforward problem, given a constant type and no concurrency.
For example (off the top of my head, untested):
template<typename T>
c... |
5,737,533 | 5,737,629 | ## macro argument concatenation not working as I expected | Shouldn't this:
#define MOGSH_CONCAT (x,y) x##y
#define MOGSH_DOUBLE (a,b) MOGSH_CONCAT(a,b)
#define MOGSH_DEFINEPROC (p) MOGSH_DOUBLE(_gt,p) options_dialog::p;
MOGSH_DEFINEPROC(AssignMainForm);
happily expand to:
_gtAssignMainForm options_dialog::AssignMainForm;
Given that _gt is not defined, _gtAssignMainForm is:
... | In the definition of a function-like macro there can be no whitespace between the macro name and the ( beginning the parameter list.
#define MOGSH_CONCAT(x,y) x##y
// ^ no whitespace allowed here
As you have it now (with whitespace), MOGSH_CONCAT is an object-like macro with a replacement list of (x,... |
5,737,681 | 5,737,721 | Implementing a skewed assosiative data cache C++ | Can someone help me on how to go about writing a program for (say 3-way) skewed data cache?
Thanks!
|
Choose three hash functions (first one should probably be the trivial one which is mod (%) cache size)
Make an array
Each new cache line should be hashed by each of those three hash functions
Evict one of the lines indicated by those hashes
Replace it with your new line
Repeat
The C++ for this should be pretty trivia... |
5,737,805 | 5,738,232 | How to make it read cin twice? | I have this bit of code:
...
ComplexNumber C1;
ComplexNumber C2;
cout << "Enter a complex number C1:" << endl;
cin >> C1;
cout << C1 << endl;
cout << "Enter a complex number C2:" << endl;
cin >> C2;
cout << C2 << endl;
...
but as I've discovered it won't wait for user input the second time and will simply leave C2 w... | I bet you did not read the i character from the input stream
|
5,737,826 | 5,738,596 | Why can't I visit this custom type with boost::variant? | The following code:
#include <boost/variant.hpp>
#include <iostream>
#include <string>
struct A
{
A()
{
}
~A() throw()
{
}
A& operator=(A const & rhs)
{
return *this;
}
bool operator==(A const & rhs)
{
return true;
}
bool operator<(A const & rhs)
... | message_t a(A());
Has the most-vexing-parse problem: declares a function rather than creates a variable. Many ways to resolve, e.g. message_t a = A();
|
5,737,846 | 5,737,874 | function declaration error, "expected constructor, destructor, or type conversion before ';' token" | I'm getting an error on line 4:
expected constructor, destructor, or type conversion before ';' token
I'm pretty weak at this point when it comes to functions, so I know that there is something wrong with my function declaration(?). Anyone have any suggestions? Thanks in advance...
#include <iostream>
using namespace... | You're not declaring a return type for shapeDetermine. If for example it is supposed to return an int, it should be declared:
int shapeDetermine(char letter);
Updating to respond to the new code the OP posted:
That new code is fine. However, if it appears after main() in the file (or in another file) then you still ... |
5,737,847 | 5,742,815 | Would data in vertex buffer change after translation? | If I load an X file and store vertex data in vertex buffer. Then, Do translation on object, Would it change data in vertex buffer?
| Of course not. You store the translation in a matrix right? So in the vertex shader you transform the vertex position by the matrix to calculate the vertex position in world space but it doesnt affect the vertex buffer
|
5,737,905 | 5,738,340 | why c/c++ allows omission of leftmost index of a multidimensional array in a function call? | I was just wondering why it is allowed to omit the leftmost index of a multidimensional array when passing the array to a function ? Why not more than one indexes? And how does the compiler find out the size with one index omitted ?
| Other answers described how the C standard handles array to pointer conversion and how this affects the function declaration, but I feel they didn't go into the why, so here I go...
In C, arrays stand for tightly packed elements in memory.
A -> _ _ _ _ _ _ ...
i: 0 1 2 3 4 5 ...
In the above example, each of the arr... |
5,737,931 | 5,738,227 | C++ lambda; class factory adaptor | Given a class factory
struct C {
C Factory(A a, B b, ...) { ... }
};
I want to transform it into a function that returns a shared pointer in an automated way. Something like:
template<T (*f)(Args...), typename T, typename... Args>
boost::shared_ptr<T> blah(Args... args) {
return boost::shared_ptr<T>(new T(f(arg... | not sure I understand the quesiton but a few points:
1) The factories should return pointers to dynamically allocated objects if you want to use them with boost::smart_ptr. Using smart pointers (which will attempt to delete objects when they go out of scope and no other smart_ptr has ownership of the object) with stat... |
5,738,233 | 5,750,932 | Compiling C++ under Linux without the runtime library | I have recently started to explore the way that the C++ runtime library is used by the generated code.
Mostly I am very curious, but I also want to evaluate the amount of work needed to develop the minimum required stuff to start a kernel in C++.
So I started to implement my own runtime library, but I have a small issu... | Okay so thanks to QuantumMechanic's link I managed to find the problem:
http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html
I just forgot my basics in linux programming, more importantly how program end is handled.
Basically, I needed to generate the syscall interrupt "exit" to handle the end of the program.... |
5,738,305 | 5,738,893 | opengl array of pool balls | i am drawing an array of pool balls in opengl using c++
the problem i am facing is the array draws in a straight line.
when i use gltranslate the balls still only translate along the line when i edit the z and y axis
what i want to do is set the balls up in a triangle shape like the breaking of a pool match
how do i u... | Do something like this:
// first of all, include the x,y position (assuming 2D, since pool) in the Ball object:
class Ball
{
//...
private:
float xpos, ypos;
//...
};
Then when you construct the array of balls, rather than just making 8 balls, you're going to want to allocate the memory on the heap so ... |
5,738,448 | 5,738,518 | Is float slower than double? Does 64 bit program run faster than 32 bit program? | Is using float type slower than using double type?
I heard that modern Intel and AMD CPUs can do calculations with doubles faster than with floats.
What about standard math functions (sqrt, pow, log, sin, cos, etc.)? Computing them in single-precision should be considerably faster because it should require less floatin... | The classic x86 architecture uses floating-point unit (FPU) to perform floating-point calculations. The FPU performs all calculations in its internal registers, which have 80-bit precision each. Every time you attempt to work with float or double, the variable is first loaded from memory into the internal register of t... |
5,738,603 | 5,740,059 | C++ Specific Sound Output? | I want to hook a circuit up to my computer, which uses the audio output as an AC current, passes certain frequencies, then rectifies it to a few LEDs, so if I write a program that lets you create a specific pattern and combination of LEDs to be lit, it would output specific frequency sounds.
How do I play a sound at a ... | You could do this with OpenAL.
You would need to generate an array containing PCM encoded data that represents your desired output, then call alBufferData() on your array with the desired sampling frequency and format. See page 21 of the OpenAL Programmers Guide for the format required by the alBufferData() function.
F... |
5,738,882 | 5,738,922 | read input separated by whitespace(s) or newline...? | I'm grabbing input from a standard input stream. Such as,
1 2 3 4 5
or
1
2
3
4
5
I'm using:
std::string in;
std::getline(std::cin, in);
But that just grabs upto the newline, correct? How can I get input whether they are separated by newline OR whitespace(s) using only iosteam, string, and cstdlib?
| Just use:
your_type x;
while (std::cin >> x)
{
// use x
}
operator>> will skip whitespace by default. You can chain things to read several variables at once:
if (std::cin >> my_string >> my_number)
// use them both
getline() reads everything on a single line, returning that whether it's empty or contains doz... |
5,739,006 | 5,739,050 | Twitter API libraries for desktop apps? | I'm looking for a way to fetch recent posts from twitter. Really I just want to be able to grab and store new posts about a certain topic from twitter in a text file. Are there any current programs or libraries which do this (prefrably C++, although python is ok too)? What would people suggest?
| you can check the API docs here, some of the projects that are listed there:
C++
QTweetLib - C++ Qt based Twitter library
QTwitLib by Bradley Lackey & Maks Zolin. C++ library for Linux, Windows, and Mac. Currently in beta. Unmaintained since 2009.
Twitcurl by Mahesh. C++ library which uses curl library for HTTP interac... |
5,739,127 | 5,739,173 | How Iterator pointers in the STL work | Hey i'm a little confused on how iterators work. Specifically a const_iterator for a class in this case. I understand that they are really just pointers to specific elements of a string or whatever you're working with, but in that case:
I would think of them as being a memory address, making it so you could not just a... | It's a bit more complicated than that. Iterators refer to the GOF design pattern of the same name, and, in C++, are applied in such a way that they look just like pointers. C++ lets you overload operators, which means that custom types can behave in specific ways when certain operators are used on them.
There are sever... |
5,739,146 | 5,739,261 | Basic question, error: substr out of range | So I'm writing a program and part of it is to deal with an array of strings, and from each element in the string array, I am trying to take out every bi-gram within the string and place that in another array. I am trying to do this by using the substr function and have tried to tweak it but I continue to get an OOR er... | string::length() is a size_t which is unsigned, so
if(lowpunct[i].length()-2 <=0)
will be a problem when a string with a length less than 2 is encountered. This is because the result of underflowing an unsigned integer is that the
number wraps around at the highest value. The for loop conditional is also wrong.
R... |
5,739,163 | 5,739,199 | Programs & Techniques for finding when a Pointer goes out of scope | I am a Software intern working on a large project in C++, & I am also a One man team. Daunting (is that how u spell it :P), yes it is, but also fun.
I am running into c++ pointers that end up pointing to NULL (not because the memory is freed/deleted but because, well I dont really know, but I suspect its because the ob... | I would suggest two different tools:
Cppcheck is a static analyser that looks at your source code and tries to identify problems (with pointers, and with a lot of other things too).
Valgrind is a runtime tool that watches all the allocations and deallocations your program performs, and ensures that they are all correc... |
5,739,384 | 5,739,509 | how to find number of elements in an array of strings in c++? | i have an array of string.
std::string str[10] = {"one","two"}
How to find how many strings are present inside the str[] array?? Is there any standard function?
| If you want to count all elements sizeof technique will work as others pointed out.
If you want to count all non-empty strings, this is one possible way by using the standard count_if function.
bool IsNotEmpty( const std::string& str )
{
return !str.empty();
}
int main ()
{
std::string str[10] = {"one","two"}... |
5,739,678 | 5,739,722 | C++: Templates and the singleton pattern | It happens so that I have a need of the infamous singleton pattern. Better yet, it happens so that I have a need of infamous C++ templates in combination with that pattern. So, what troubles me is this:
template <class T>
class PDatabaseTable
{
...
static PDatabaseTable <T> & instance()
{
static PD... | There will only be one instance for each type T, just as, if it weren't a template, there would only be one instance.
The function is inline, meaning that although it can be defined in multiple compilation units, after linking there will be only one version of it, and only one instance of any local static objects.
|
5,739,937 | 5,740,094 | Using getline(cin, s) after cin | I need the following program to take the entire line of user input and put it into string names:
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
getline(cin, names);
With the cin >> number command before the getline() command however (which I'm guessing is the issue), ... | cout << "Enter the number: ";
int number;
if (cin >> number)
{
// throw away the rest of the line
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
cout <... |
5,740,155 | 5,740,901 | Access v-table at run-time | Is it possible to access a function's v-table at runtime? Can meta-information such as the number of different function versions be determined? This might be more of a theoretical question, but could a developer put a cap on the number of classes that can extend a given base class by making sure the v-table never excee... |
Is it possible to access a function's v-table at runtime? Can meta-information such as the number of different function versions be determined?
Not in a portable way. The standard does not even have the concept of virtual table, it is more of an implementation detail than a requirement, even if all implementations I ... |
5,740,296 | 5,740,305 | Missing default argument - compiler error | void func ( string word = "hello", int b ) {
// some jobs
}
in another function
//calling
func ( "", 10 ) ;
When I have compiled it, compiler emits error ;
default argument missing for parameter
How can I fix it without changing anything, of course, such as not making "int b = 0" ?
Moreover, I want use that... | You can't have non-default parameters after your default parameters begin. Put another way, how would you specify a value for b leaving word to the default of "hello" ?
|
5,740,310 | 5,740,343 | No == operator found while comparing structs in C++ | Comparing two instances of the following struct, I receive an error:
struct MyStruct1 {
MyStruct1(const MyStruct2 &_my_struct_2, const int _an_int = -1) :
my_struct_2(_my_struct_2),
an_int(_an_int)
{}
std::string toString() const;
MyStruct2 my_struct_2;
int an_int;
};
The error is... | In C++, structs do not have a comparison operator generated by default. You need to write your own:
bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return /* your comparison code goes here */
}
|
5,740,379 | 5,741,073 | Difference between a C++ string and a C-string ( .c_str() ) |
Possible Duplicates:
Why does std::string not provide a conversion to const char*?
Why doesn't std::string provide implicit conversion to char*?
case 1 :
void readFile ( const string& inputfile ) {
ifstream in ( inputfile );
}
case 2:
void readFile ( const string& inputfile ) {
ifstream in ( inputfil... |
What is the real difference between a C++ string and a null-terminated sequence of characters (C-string) .c_str() ?
A C++ std::string object encapsulates:
a char array storing the semantic (presumably textual) value
some implementations store short text strings directly in the std::string object
otherwise heap memo... |
5,740,578 | 5,740,753 | Why "const" is needed here: VS C2664 | I copy code from MSDN
It says that "In Visual C++ 2005, the compiler now enforces the C++ standard requirements for applying const. The following sample generates C2664."
// C2664d.cpp
// C2664 expected
#include <windows.h>
void func1(LPCSTR &s)
{
}
void func2(LPSTR &s)
{
func1(s);
}
int main()
{
return 0;
}
... | (Those LPCSTR/LPSTR typenames only obfuscate the code. )
The issue you have here can be expressed in the following succinct way
char *p = NULL;
const char *&r = p; // ERROR
This code does not compile for the very same reason your original version does not compile: such reference initialization is illegal in C++. In yo... |
5,740,590 | 5,740,666 | SwigPyObject and JSON communication inside python code | Intro.
I have a C++ application, I use SWIG to launch GetObjects and PutObjects methods which are defined in python code. GetObjects method opens JSON formated file, takes objects from there and returns back them to C++ application. While the PutObjects method gets objects from C++ application, opens JSON formated file... | You should be able to use the "dir" function to get a list of attributes of an object.
Here is example which grabs all non function user created attributes (called "properties"):
import inspect
class MyObject(object):
def __init__(self):
self.b = 1
self.c = 'a'
def func(self):
pass
obj... |
5,740,976 | 5,741,027 | Using a Random class in a static way | I am making a simple Random class:
class Random
{
public:
static bool seeded = false;
static void SeedRandom( int number )
{
srand(number);
}
static int GetRandom(int low, int high)
{
if ( !seeded )
{
srand ((int)time(NULL));
}
return (rand() ... |
c++ doesn't allow declaring a whole class as static
Of course it does.
class RandomClass
{
public:
RandomClass()
{
srand(time(0));
}
int NextInt(int high, int low)
{
return (rand() % (high - low)) + low;
}
}
RandomClass Random; //Global variable "Random" has static storage dur... |
5,741,146 | 5,741,296 | Template refactoring | Let's imagine we have several type of elements, and we want to create a
'manager' for every type of them. The manager takes care of the
creation, activation/deactivation and removal for any of the elements
(we assume the user will no create/destroy the instances of these elements
without using the manager.
A very sim... | Factor out that specific behavior into a policy:
#include <set>
struct cached_tag;
struct noncached_tag;
template<typename Tag>
struct ElementMngrCachePolicy;
template<>
struct ElementMngrCachePolicy<cached_tag>
{
template<typename T>
static void removeFromCache(T* const element) { /*impl...*/ }
templat... |
5,741,203 | 5,741,279 | How can I change this loop to not use continue? | I used the continue statement to make this simple program and got the desired output.
for(m=1;m<=3;m++)
{
for(n=1;n<=2;n++)
{
if(m==n)
continue;
cout<<m<<" "<<n<<endl;
}
}
output:
1 2
2 1
3 1
3 2
Now I want it without using the coninue statement. Is there any way to make it?
| My solution is even simpler. It doen't use even if:
for(int m=1;m<=3;m++)
{
for(int n=1;n<=2;n++)
{
m != n && (cout<<m<<" "<<n<<endl);
}
}
Output:
1 2
2 1
3 1
3 2
Demo : http://www.ideone.com/rMSuK
Note that I'm not going to do this in production code, but for this particular problem, thinking of it as a... |
5,741,231 | 5,811,798 | MFC image from array | What is the fastest/easiest way to convert an array (of double) into a MFC-Bitmap to be displayed in a Picture Control?
| I would start with a CMemDC, where you can set every pixel by CDC::SetPixel(), and then BitBlt it over to a real CDC.
If you want a real bitmap, look here: Creating HBITMAP from memory buffer
|
5,741,607 | 5,741,647 | difference in implementation of map and dictionary | I know what the difference is in terms of where a map or where a dictionary is used, but what I wondered is why a Dictionary<TKey, TValue> in .NET supposedly uses, from what I've read here, a linked list under the covers and I know that a std::map<K,T> (C++) is implemented as a red-black tree.
Why aren't they the same ... | Dictionary<> is a hash table, akin to std::unordered_map<>.
SortedDictionary<> is a red-black tree, akin to std::map<>.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.