question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
7,052,966 | 7,052,998 | Defining >> operator | I can not implement >> operator
ostream&operator>>(Mode&refMode,ostream&os)
to perform chaining operations as
refMode.iMode>>(refMode.jMode>>os)
Would you please provide me an implementation of it ?
| As Oli said in his comment, we normally define operator << for streaming. You shouldn't change the usual semantics of the operator just to be fancy. That said, I don't see any other technical impediments for your idea. Example:
#include <iostream>
class A
{
int i;
public:
A(int i = 0):i(i){}
};
std::ostream& ope... |
7,053,017 | 7,053,069 | Vector of fixed array in c++98 | I need to store an indeterminable number of triangles in a vector, therefore, it would be something like:
std::vector<Point[3]>
But that is not valid C++98. What are other solutions that do not involve a triangle struct?
Thanks
|
You may define a struct
You may use pair<pair<Point,Point>,Point> type
If you can use latest C++, there are many options and one of them is using std::tuple. If there are more of such cases, you may implement your own tuple class taking 3 or more types.
|
7,053,472 | 7,053,537 | Other methods to exploit the poll() function (user-space)? | I'm trying to find better methods to handle the events of a polled socket (fd). I'm stuck on this to exploit the poll() function with a different pollfd like this:
#define out std::cout
#define el std::endl
#define line(string) out<<string<<el
class int_t
{
private:
int _int;
int _owner;
public:... | That looks very convoluted. If you want to encapsulate the poll functionality in an object, don't encapsulate an int, encapsulate the poll. Something like this:
class poller_callback {
public:
void handle_pollin(int fd) = 0;
};
class poller {
public:
poller(const vector<int>& fds);
void... |
7,053,497 | 7,053,521 | What are these errors? how can I fix them? | I am learning c++ and I am writing a card dealer program. When I compile my code and I get these errors:
dealer3.cpp:12: error: expected initializer before ‘int’
dealer3.cpp:33: error: expected constructor, destructor, or type conversion before ‘=’ token
dealer3.cpp:34: error: expected constructor, destructor, or type ... | Actually, this is a nice case where indenting the code would solve your problem (or make the solution very obvious), as it would show up several errors in with your braces. You have several lines of code that are outside of any function that don't belong there.
Some formatting hints for you:
Indent each nested block o... |
7,053,538 | 7,053,808 | How do I encode a string to base64 using only boost? | I'm trying to quickly encode a simple ASCII string to base64 (Basic HTTP Authentication using boost::asio) and not paste in any new code code or use any libraries beyond boost.
Simple signature would look like:
string Base64Encode(const string& text);
Again I realize the algorithm is easy and there are many libraries/e... | I improved the example in the link you provided a little:
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/ostream_iterator.hpp>
#include <sstream>
#include <string>... |
7,053,680 | 7,054,642 | select records from db and insert into C++ map | Can someone suggest me a good example or link to select records from MySQL and insert the records into a map so I can do the analysis in C++.
I am trying to pull in price data from the db, so I have a transaction date and sale price.
I don't want to go through the intermediate step and write the records to a .csv file.... | You will need to use the C++ connector. You can download it from this link.
Here's the wiki page to get you started.
Edit: I haven't tested this myself, but something like this should work:
map<int, string> results;
sql::mysql::MySQL_Driver* driver = sql::mysql::get_mysql_driver_instance();
sql::Connection* con = driv... |
7,053,701 | 7,053,802 | md5sum a file that contain the sum itself? | I have written a small app in C++ consisting of a single EXE file.
I want to put in its "about" dialog the md5sum of the executable itself. It should be embedded statically into the executable (so that can be seen from hex editor), rather than computed on the fly.
| As both @Shi & @matthewdaniel have already said, this can't be done directly.
However a couple of workarounds are possible:
Calculating MD5 of your application, and packaging your executable inside a container app that will simply extract it and check it's MD5
Compiling your code and hashing only the code segments... |
7,053,966 | 7,053,977 | When will compiler generate default constructor for a derived class | Here is my observation:
The compiler will NOT generate a default constructor for a derived class whose base class has defined a constructor.
// example
class ClassCBase
{
public:
ClassCBase(int i) {}
};
class ClassC : public ClassCBase
{
};
int main()
{
ClassC c; // error C2512: 'ClassC' :
// ... | The compiler won't generate a default constructor if the superclass has no default constructor. In other words, since the superclass constructor needs an argument, and the compiler can't be expected to know what an appropriate default value is, the compiler will fail to generate a useful default constructor. But if you... |
7,054,080 | 7,054,162 | managed c++ code doesn't find function implementation | I have 3 files:
main ".h" file - contains implementation of a simple WinForm (managed c++)
fold/file.h
fold/file.cpp
(file.h and file.cpp are not represent a class)
I have a function "func()" which its declaration is in fold/file.h, and its implementation is in fold/file.cpp.
There is include "fold/file.h" in main.h
... |
when I put the implementation of "func()" in fold/file.h there is no error.
Are you compiling all the source files ? I suspect you are not because when you bring the definitions to the header file and include it in the main source file, pre-processor actually copies it to the main source file. So, while compiling and... |
7,054,180 | 7,054,192 | Virtual function keyword | Is there any difference between declaring inherited virtual function in a child class with the "virtual" keyword or not, considering I want to call fun appropriate to my objects' type. Look at the comments.
#include <cstdio>
struct A{
int a;
A():a(5){}
virtual int fun(){return a+1;}
};
struct B: public A{
... | Overriding functions in derived classes are implicitly declared "virtual" if the corresponding function in the base class is virtual. Just make sure you got the exact same signature, or you might inadvertently hide the original function and declare a new one!
In C++0x, feel free to make liberal use of the override spec... |
7,054,209 | 7,054,276 | c++ program successfully build, No output, only show stack trace | Successfully Build, but Netbeans Run outputs stack trace
Stack trace:
Frame Function Args
0022C694 7570EFA3 (00000108, 0000EA60, 00000000, 0022C7B8)
..............
End of stack trace
I am reading a file line-by-line and check if they have vowel using C++ class concept.
I have tested read a file line-by-line and... | There are a couple of things. First one is that the pwd member of Password is not initialized, which will probably cause setPassword(...) to fail on the first call. You could initialize in your constructor like so (argument renamed to avoid confusion):
Password(const char *apwd) : pwd(0) {
setPassword(apw... |
7,054,538 | 7,054,724 | Custom glBlendFunc a lot slower than native | I'm trying to do my own custom glBlendFunc through fragment shaders, however, my solution is a lot slower than the native glBlendFunc, even when they do the exact blending function.
I was wondering if anyone had any suggestion on how to do this in a more efficient way.
My solution works something like this:
void draw(f... | Your best bet for improving the performance of FBO-based blending is NV_texture_barrier. Despite the name, AMD has implemented it as well, so if you stick to Radeon HD-class cards, it should be available to you.
Basically, it allows you to ping-pong without heavyweight operations like FBO binding or texture attachment ... |
7,054,662 | 7,054,741 | Why do certain C/C++ functions use pointers as parameters? | I'm coming from C# and I'm learning C++ (with this tutorial) so I have a relatively insubstantial amount of knowledge on memory, but the only use I see in pointers is "saving space" and iterating through arrays. So why do functions like the scanf function take pointers as parameters? For instance:
printf("What's your n... | C and C++ pass variables by value; the formal parameter is a different object in memory from the actual parameter. Thus, if the formal parameter is modified in the function, the value of the actual parameter isn't changed.
By passing a pointer, the function can modify the contents of the actual parameter:
void swap(in... |
7,054,685 | 7,054,725 | Are destructors run when calling exit()? |
Possible Duplicate:
Will exit() or an exception prevent an end-of-scope destructor from being called?
In C++, when the application calls exit(3) are the destructors on the stack supposed to be run to unwind the stack?
| No, most destructors are not run on exit().
C++98 §18.3/8 discusses this.
Essentially, when exit is called static objects are destroyed, atexit handlers are executed, open C streams are flushed and closed, and files created by tmpfile are removed. Local automatic objects are not destroyed. I.e., no stack unwinding.
Cal... |
7,054,772 | 7,054,882 | Segmentation fault with glBufferData() | I can't work out why this code is seg faulting:
AxesMarker::AxesMarker(float size)
: size_(size), vbo_vertices_(0), vbo_elements_(0)
{
Vertex vertices[6] = {
Vertex(Color4f::RED, Vector3f::ZERO, Vector3f::ZERO),
Vertex(Color4f::RED, Vector3f::ZERO, Vector3f(size_, 0.0f, 0.0f)),
Vertex(Color4f::... | Is your Vertex class a plain old data type? Does it have any virtual functions which might mean it also has a vtable? Can you try re-writing this code using an array of plain floats,(just to test your calls to glBufferData are working). From what I can tell though, it looks like you are using glBufferData correctly, bu... |
7,054,952 | 7,055,102 | Type trait for moveable types? | I'm trying to write a template that behaves one way if T has a move constructor, and another way if T does not. I tried to look for a type trait that could identify this but have had no such luck and my attempts at writing my own type trait for this have failed.
Any help appreciated.
| I feel the need to point out a subtle distinction.
While <type_traits> does provide std::is_move_constructible and std::is_move_assignable, those do not exactly detect whether a type has a move constructor (resp. move assignment operator) or not. For instance, std::is_move_constructible<int>::value is true, and conside... |
7,054,961 | 7,054,967 | Compile error i can't figure out | im getting a "storage size of ‘data’ isn’t known" when i try to use a certain struct.
Code:
ioHelper.h:
#ifndef IOHELPER_H_
#define IOHELPER_H_
typedef struct fileValues data;
struct fileValues ioInput(FILE* file,int dim,int sign);
#endif /* IOHELPER_H_ */
ioHelper.c:
struct fileValues
{... | This is because when compiling map.c the compiler can't see the full definition of the struct in IoHelper.c.
You probably only included IoHelper.h, which has the (incomplete) declaration, not the definition.
So you cannot declare a variable of that struct type inside of map.c unless you
include IoHelper.c (BAD IDEA)
... |
7,055,183 | 7,055,236 | How can I clear the input buffer in a c++ application? | I make a lot of simple console c++ applications and one problem I am facing is the input buffer. I have tried cin.ignore and flush(), but they don't seem to be working for me.
If I have code such as:
cin >> char1;
cin >> char2;
and I press: 1 (space) 2 (Enter), with just one enter, the 1 is stored to char1 and the 2 ... | You could use getline to read the whole line at once, then std::string at if you need the first char, or use an isstringstream if you need the first number.
char char1;
std::string input;
getline(std::cin, input);
if (!std::cin.good()) {
// could not read a line from stdin, handle this condition
}
std::istringstrea... |
7,055,228 | 7,055,246 | Lifetime of vector::push_back() elements | I want to confirm what I think I understand about the lifetime of objects which have been push_back()'ed on an std::vector. What I read says that the elements in the vector are copies. So, is the usage below OK? Specifically, is the variable s in f2() a different instance of an std::string than the one that is push_... | Yes that is correct. A copy of string s gets stored during push_back. Check the doccumentation for detail. It states:
void push_back ( const T& x );
Adds a new element at the end of the vector, after its current last element. The content of this new element is initialized to a copy of x.
Parameters
x
Value to be copi... |
7,055,242 | 7,055,273 | Is it bad practice to have a set method without its own get method? | Let's say I have a class (the name circle was random and has no significance):
Class circle{
double colorFrequency_;
public:
void setColor(double colorFrequency){ colorFrequency_=colorFrequency; }
void setColor(string colorName){ colorFrequency_=colorNameToFrequency(string colorName); }
double getColor... | It depends on whether you want the member value to be obtained by the users of your class.
So unusual or not, you should stick to what your design demands.
|
7,055,411 | 7,055,418 | put class with pointer that is malloc allocated into map container | I'd like to use the map for key/member search, the problem is that the class contains a member of buffer allocated by the malloc call.
struct Key {
int key1;
int key2;
bool operator < (Key & a) { .... }
};
struct Entity {
unsigned char *data;
};
typedef std::map(Key, Entity) TMap;
Then I can insert... |
You should be using new and not malloc in c++. And
You should use Smart pointers instead of raw pointers/naked pointers inside your container.
STL containers do not take the responsibility of deallocating an element which is allocated on the freestore. Which means you would have to deallocate them explicitly. The ... |
7,055,433 | 7,055,445 | how to properly allocate memory in C++ in low memory conditions | I have seen resources show two ways of allocating memory while ensuring that there was enough memory to complete the operation.
1) wrap the 'new' operation in a try/catch since it'll return std::bad_alloc (?)
try { ptr = new unsigned char[num_bytes]; } catch(...) {}
2) check the assigned pointer for null after the '... | If you are using the standard implementatin of new which throws exception, then first one is correct.
You can also use the second one if you use nothrow as:
ptr = new (nothrow) unsigned char[num_bytes];
if(ptr == NULL) { ... }
|
7,055,557 | 7,055,567 | Throw bad_cast when converting pointers with dynamic_cast? | dynamic_cast throws bad_cast exception if you cast a reference but as I know in the standard pointers are considered as references, i.e. a pointer is a type of a reference.
So should I get bad_cast when casting pointers?
This question arose from the try-catch block from this page. Is this try-catch block inappropriate?... | No with pointers in case of a bad cast, dynamic_cast will return a null.
Also, dynamic_cast works only on Polymorphic classes, So if you are talking about built in data types(from the link in your question) then static_cast is what you should be using.
And btw, References are NOT pointers.
|
7,055,669 | 7,055,738 | C++ object function to function pointer | I'm using a C library inside my C++ app. The library has a function with the following signature:
void awe_webview_set_callback_js_callback(awe_webview* webview, void (*callback)(awe_webview* caller, const awe_string* object_name, const awe_string* callback_name, const awe_jsarray* arguments));
I'm trying to set a fun... | The fact that callbacks receive awe_webview pointer more or less proves that comparing them is what they expect you to do.
However, I would modify your solution to use a global map between webviews to BattleScreens:
static std::map<awe_webview*, BattleScreen*> gWebViewBattleScreen;
Then have one global callback that p... |
7,055,740 | 7,055,836 | map inserting key values into wrong key? | I have been having this problem for awhile with my code, looking for my mistake I can't see it. I have a map, map I am mapping keywords to the values.
My problem is sometimes when inserting keyword = "Blue" the value is inserting into the Key for "Red".
So instead of,
Key: Red, Value: obj1, obj2
Key: Blue, Value: obj3... | I see no declaration for keywordObject, so I shall assume it's a global. The case of adding a new object to a keyword which is already present is dealt with in the else. What is the value of keywordObject in this case? Who sets it?
There are a number of other problems with this code, some mentioned in other answers an... |
7,055,875 | 7,055,931 | A rather unusual bison error | I was teaching myself Bison and headed over to wikipedia for the same and copy-pasted the entire code from the example that was put there [ http://en.wikipedia.org/wiki/GNU_Bison ]. It compiled and works perfect. Then, I OOPed it by adding in a bit of C++. Here's is my new Parser.y file:
%{
#include "TypeParser.h"
#in... | In the rule expr TOKEN_PLUS expr $1 is the first expression, $2 is TOKEN_PLUS, and $3 is the second expression. See the bison manual.
So the semantic action needs to change from your { $$ = new Addition($1, $2); } to { $$ = new Addition($1, $3); }.
|
7,056,121 | 7,056,162 | Mistake, or valgrind/gcc bug? | When running valgrind on the following program the assertion fails:
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <wchar.h>
#include <assert.h>
#include <signal.h>
#include <stdlib.h>
#include <ucontext.h>
stati... | It will work if you use precise exceptions.
valgrind --vex-iropt-precise-memory-exns=yes ./your_program
This page precisely describes what you are trying to do :-))
If you're using signals in clever ways (for example, catching SIGSEGV,
modifying page state and restarting the instruction), you're probably
relying ... |
7,056,333 | 7,056,346 | How to load 3D models in OpenGL C++? | I am trying to load 3D models. How do I to read the data in the model file?
For an example, this is the data:
VERTICES
80 21 32
32 34 17
14 93 56
33 54 87
MODEL_SCALE 5
I know the data in 3D models is not like this, but how will I read the 'vertex data' and the 'model scale amount'?
| OpenGL doesn't do this for you. You should write your own parser, store the readed datas into your defined data structures and use OpenGL primitives to render them.
Here's a nice tutorial.
|
7,056,461 | 7,056,492 | Unable to load some functions from DLL with GetProcAddress() | I'm trying to build a DLL which I would later like to inject into some processes using the SetWindowsHookEx() function. Strange thing is that when I try to load the DLL and try to get use GetProcAddress to get the address of the procedure contained within it, it returns NULL if I try to get the address of the CBT messa... | The calling convention changes the name mangling. __stdcall functions always have their names prepended by _ and mangled in some other ways too, so the link fails, but the __cdecl function isn't mangled and so it's found.
To import from a DLL that you built with __declspec(dllexport), you should always include a heade... |
7,056,529 | 7,058,154 | How to remove all rows and child rows from QTreeview | I don't know why I have trouble removing all rows and sub rows from qtreeview
I'm using QStandardItemModel as the model. Now here is my code that doesn't work.
What could be the problem?
QModelIndex FirstQModelIndex;
QModelIndex parentQModelIndex;
int iMdlChidCound = m_model->hasChildren();
if(iMdlChidCound > 0)
{
... | It seems like a lot of what you're doing is superfluous. If your only goal is to remove all the rows from the model, you could probably just use QStandardItemModel::clear
In your code you're jumping between the model and the items in a way you don't have to.
if(m_model->hasChildren()) {
m_model->removeRows(0, m_m... |
7,056,740 | 7,100,082 | Triangle fit inside another triangle | Given the lengths of the sides of 2 triangles. Determine if the second triangle can fit inside the first triangle?
For more detailed info read the full problem statement below:
http://acm.timus.ru/problem.aspx?space=1&num=1566&locale=en
My implementation below tries all the (3!)^2 possible combinations of aligning the ... | Use epsilon (1e-10) when comparing doubles!
|
7,056,813 | 7,056,834 | How do I find the 'namespace keyword' of an included file? | I'm a novice C++ programmer.
How can I find out the namespace (is this the right word in this context?) for an include like 'iomanip' or any other?
When using 'std::cout', I don't know why it's 'std' and not something else.
I hope my question is clear and worth asking.
PS: My first post here :)
| How did you know that cout existed in the first place?
Because you've read the friendly manual, the language standard, a good book, or an online reference. The same applies to everything: Your documentation or reference will tell you the namespace in which you find your types.
Generally, everything that's part of the C... |
7,056,931 | 7,056,964 | Insert properties into last element in a vector | EDIT Sorry! This code actually works correctly; I was looking at the wrong error. Thanks to everyone for their input.
I want to be able to directly access the last element of a vector<> in C++. Currently, I push_back() a temporary variable (of a custom type), however I'd much rather put data straight into the vector. T... | Why won't
customArray.back().colour[0] = 1;
work?
It does work! Try again :)
|
7,057,022 | 7,057,184 | Is it safe to keep C++ pointers in C#? | I'm currently working on some C#/C++ code which makes use of invoke. In the C++ side there is a std::vector full of pointers each identified by index from the C# code, for example a function declaration would look like this:
void SetName(char* name, int idx)
But now I'm thinking, since I'm working with pointers couldn... | Yes, no problem. Native memory allocations never move so storing the pointer in an IntPtr on the C# side is fine. You need some kind of pinvoked function that returns this pointer, then
[DllImport("something.dll", CharSet = CharSet.Ansi)]
void SetName(IntPtr vector, string name, int index);
Which intentionally lies... |
7,057,056 | 7,057,073 | Casting changes value strangely | Why does a1=72 instead of 73 in this (terrible) snippet of C++ code ?
#include <iostream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
double a = 136.73;
unsigned int a1 = (100*(a-(int)a));
cout << (a-(int)a) << endl; // 0.73
cout << 100*(a-(int)a) << endl;... | If you increase the output precision, you'll see that (a - (int) a) prints 0.7299999999999898.
Therefore, the truncation of this value (which you obtain when you cast it to an int) is indeed 72.
(Updated codepad here.)
|
7,057,292 | 7,057,309 | How to put our own function declaration in iostream library in c++? | ostream& tab (ostream &o)
{
return o << '\t';
}
I want to put this declaration in iostream library..how can i do this??
| You can't. The contents of the iostream library are defined by the C++ standard, and potentially shared by every C++ program in the system. Although you can (in practice, this is technically forbidden by the standard) inject things into the std namespace for your own program (this is a bad idea however due to potential... |
7,057,526 | 7,057,541 | Unexpected result when looping chars in C++ | I'm using the book "Programming Principles and Practice using C++" to learn programming and one of the exercises is looping through the characters a-z using a while-loop.
Now, I have programmed with C++ and other languages before, so I decided to try to use as few lines as possible (while still using a while-loop). How... | Short answer is that you have a bit of Undefined Behavior because you're both modifying and using the value of the variable ch, via separate sub-expressions, in the same expression.
The Right Thing(TM) to do here is to use the most practical loop for the task at hand:
#include <iostream>
int main(){
for(char ch = '... |
7,057,899 | 7,060,168 | Makefile for compiling .idls | I'm writing my first Makefile to compile some CORBA .idl definitions for use as part of a larger system. I use omniORB's omniidl program which takes file.idl and creates file.hh and a fileSK.cc. Each .idl has no dependencies and is created with the command omniidl -bcxx file.idl.
From reading the GNU Make tutorial it s... | The dependencies of your all target should be a list of object files, instead of the list of idl files. Something like this:
all: $(patsubst %.idl, %SK.o, $(wildcard *.idl))
(For clarity, you could also introduce a variable to hold the list of idl files, and then use a substitution reference to get the list of object... |
7,058,016 | 7,058,030 | Is it possible to use "this" in c++ to create local object in member function? | I have a question regarding "this" keyword. I have a class called "BiPoly", which represents bivariate polynomial. There is a member function called BiPoly<NT>::DifferentiateX(), which gets Partial Differentiation wrt X, and it's self-modified.
template <class NT>
BiPoly<NT> & BiPoly<NT>::differentiateX() {
if (yd... | You can use copy constructor on *this, yielding a copy of your polynomial object which you then differentiate and evaluate:
BiPoly<NT> copy(*this);
copy.DifferentiateX();
NT val = copy.eval1(arg);
Depending on how do you store the coefficients (e.g. in standard vector), you might not even need to actually write the co... |
7,058,098 | 7,058,427 | Variadic Templates Multidimensional Array Container | In the C++0x Variadic Templates Proposal paper Link there is an example of a class which supports an arbitrary number of dimensions. I have copied it below:
template<typename T, unsigned PrimaryDimension, unsigned... Dimensions>
class array { /* implementation */ };
array<double, 3, 3> rotation matrix; // 3x3 rotation... | Here is a very simple implementation (compiled with gcc4.6.1) that demonstrates the recursion involved in getting the array type right - if there is some other specific implementation detail you are interested in, please let us know:
template<class T, unsigned ... RestD> struct array;
template<class T, unsigned Primar... |
7,058,167 | 7,058,204 | Need help regarding Template class instantiation | Let me present my problem with an example :
template <typename T> class a{
public:
T data;
a():data(T()){}
a(T temp): data(temp) {}
};
So if write in main() like
a(30);
a("String");
So according to the template argument deduction rule , it should be able to generate the first temporary class as a<int>(30)... | Template parameter deduction from arguments only works for functions, never for classes. Until you know the type of the class, i.e. all its template parameters, you don't even know which member functions the class has!
So, you always have to say the template parameters if you want to construct an object directly:
a<int... |
7,058,254 | 7,058,350 | Calling C# function from C++? | I'm writing an app in monotouch which also makes use of a C++ library, so I've been using p/inoke to call C++ functions from C# to do a variety of things. However there is emerging a few scenarios where I would like the C++ code to call C# functions instead.
So something like:
void CPlusPlusFunction(Pointer* stuff)
{
... | Yes you can. However the AOT compiler, used for MonoTouch code compiled for devices, must be aware of such callback so it can generate the appropriate code. As such your callbacks must be decorated with the [MonoPInvokeCallback] attribute.
http://developer.xamarin.com/guides/ios/advanced_topics/limitations/#Reverse_Cal... |
7,058,323 | 7,058,387 | c++ explicit instantiation -- function templates -- replace a implicit instantiation to learn it | Im reading c++ primer plus and having some issues understanding how implicit instantiation works. I havent learned classes yet, so I am just dealing with functions. I think I understand the basics of implicit instantiation (function templates) but I just dont understand explicit instantiation. I have below a function t... | Just do a Show<int>(c, d) Notice that I've explicitly instantiated the int version, but passed the char parameters. That's (a rather simple take on) explicit instantiation, but you might be actually referring to explicit specialization.
|
7,058,339 | 7,058,373 | When to use references vs. pointers | I understand the syntax and general semantics of pointers versus references, but how should I decide when it is more-or-less appropriate to use references or pointers in an API?
Naturally some situations need one or the other (operator++ needs a reference argument), but in general I'm finding I prefer to use pointers (... | Use reference wherever you can, pointers wherever you must.
Avoid pointers until you can't.
The reason is that pointers make things harder to follow/read, less safe and far more dangerous manipulations than any other constructs.
So the rule of thumb is to use pointers only if there is no other choice.
For example, retu... |
7,058,412 | 7,058,444 | Can I include global static member? | There are few global variables which are static in one of the header files. I see these variables are used in the associated .cc files. So, looks like this has no issues.
My questions are:
Whats the difference between including a global variable vs static global variable ?
I know static global doesnt have visibility o... | (1) If you put a global variable in a .h file and include it in various .cpp/.cc files then it will be defined multiple times for every file. So you are most like to get a linker error.
To overcome that, mostly you are likely to use extern keyword:
// myfile.h
extern int i;
and define that in only one translation unit... |
7,058,457 | 7,059,949 | Can a call delete on the pointer which is allocated with the placement new? | Can we call delete on the pointer which is allocated with the placement new? If no then why? Please explain in details.
I know that there is no placement delete. But I wonder why just delete opetator can not delete the memory without caring how that memory on which the pointer points is allocated?
delete is doing two... |
EDIT1: I know that there is no placement delete. But I wonder why just
delete opetator can not delete the memory without caring how that
memory on which the pointer points is allocated?
Because each flavour of memory allocation uses some implementation specific tracking of the memory (usually a header block that ... |
7,058,547 | 7,058,653 | Am I using Grand Central Dispatch correctly? | I have a procedure that calculates the outcome of a game by random sample; it is passed a number of iterations, runs a loop of that size storing the outcomes in a local variable (subHits), then after the loop is done, adds the totals from the local variables into a class level member variable (m_Hits), to wit:
void Gam... | You're getting lucky. You should either have a dedicated (serial) queue for updating the shared state, or use OSAtomicAddSize to add to it. Without this you'll be losing updates occasionally.
|
7,058,564 | 7,058,582 | Dock window in win32 c++ | Can you dock a child window control in C++ win32 API (like are there WS_* styles or something), or do you always have to listen for the WM_SIZE message on the parent window and manually re-layout/fill all the children?
| There is nothing directly available in the WinAPI that will automate this, it's generally implemented by framework wrappers (like MFC...). However, there are a few libraries (such as this one) that you could use as an alternative to implementing it from scratch.
|
7,058,577 | 7,058,610 | Defining methods of class with template parameters | File main2.cpp:
#include "poly2.h"
int main(){
Poly<int> cze;
return 0;
}
File poly2.h:
template <class T>
class Poly {
public:
Poly();
};
File poly2.cpp:
#include "poly2.h"
template<class T>
Poly<T>::Poly() {
}
Error during compilation:
src$ g++ poly2.cpp main2.cpp -o poly
/tmp/ccXvKH3H.o: In function `main':
... | The full template code must appear in one file. You cannot separate interface and implementation between multiple files like you would with a normal class. To get around this, many people write the class definition in a header and the implementation in another file, and include the implementation at the bottom of the h... |
7,058,666 | 7,138,337 | How can I draw around a rectangle? | I'm using openGL to draw some animation.
I want to draw the animation in an area around a rectangle.
That rectangle are should be transparent, to show whatever windows happen to be there, and leave that to regular windows MFC drawings.
I know there should be away to do it with clipping. But since whatever is in that re... | Solution:
If you are drawing over unrelated windows, you should use Stencil buffer.
This can be used as a masking layer to decide where you want to draw.
If you have an MFC window with a child window, you can create the "father" window with the following style: WS_CLIPCHILDREN
|
7,058,719 | 7,058,789 | Random class for c++ | I want for a project in C++, to have a class that has the functionality that Random class has in java or in c#
I have found this one, http://www.dreamincode.net/code/snippet342.htm but it has bugs and I can't quite fix them right now.
Could you point out the bugs and their fixes, or suggest another implementation?
| Try this: http://bedaux.net/mtrand/
|
7,058,722 | 7,060,044 | Posix thread tutorial | I'm looking for a comprehensive pthread tutorial. I considered buying Programming with posix threads but this book seems is bit dated. Other online tutorials like this are very basic. Can someone please suggest a good and complete pthread tutorial.
| Lawrence Livermore National Laboratory has an excellent tutorial at:
https://computing.llnl.gov/tutorials/pthreads/
|
7,058,934 | 7,058,960 | C++ code outputting negative values | I wrote up a solution for a puzzle-type website. On XCode with the latest g++, my code compiles fine. On their website (and codepad), my output is negative. Could someone help me understand why, because I'm honestly stumped.
#include <iostream>
#include <cmath>
#include <vector>
#include <map>
using namespace std;
ve... | Very likely culprit is that CodePad and the other site are compiling on a 32-bit system, where a long is 4 bytes long (http://codepad.org/W00vCFIN). On OS X, everything defaults to 64-bit, and on those systems (but not Windows), a long is 8 bytes long. As such, you are overflowing a computation at some point.
If you de... |
7,058,947 | 7,058,963 | Can you recommend a good cross-platform application development framework? | I am looking to tap into the immense wisdom and experience of the Stackoverflow community to help me choose a good cross-platform application development framework.
The target application is a desktop graphics app supporting as many existing desktop environments as reasonable (Linux, BSD, Windows, Mac). Ideally Open ... | Qt covers just about everything:
is proper open source, with active development and a vibrant community
the portability aspect is covered: goes from embedded to big systems with everything (particular Windows, Mac OS X, Linux) in between; *BSD should not be an issue either,
the GUI aspects,
has good Open GL support
... |
7,059,426 | 7,059,493 | Need help understanding how luabind instantiates classes | Let's say I have a class like this:
class A
{
public:
A(){}
~A(){}
};
And expose it to Lua via Luabind like this:
module(luaState)
[
class_<A>("Foo")
.def(constructor<>())
];
And finally instantiate it in a script like this:
A = Foo();
What is the actual 'state of existence' of A at that poi... | Object lifetime is very simple with Luabind. You don't need to understand the gory details of what Luabind does internally to get it.
Lua owns the objects that are created by Lua directly. So if you allocate an object with constructor syntax in Lua, that object is owned by Lua. When the object is no longer referenced i... |
7,059,549 | 7,059,563 | C++ Multi-line comments using backslash | Can // style comments be continued to the next line by using a back slash, like multi-line macros? E.g.
// here is a comment \
and this is more comments \
const char* x = "hello"; // this line of "code" is actually still a comment
int x = 5; // and now an actual line of code
| Yes. Lines terminated by a \ are spliced together with the next line very early in the process of translation. It happens at phase 2 of translation, before comment removal and before preprocessor has a chance to do its work.
Comment recognition and removal takes place at phase 3. For this reason you can turn a // comme... |
7,059,758 | 7,059,783 | the extension of a source file | A compiler checks the syntax of source code from the text file. Why is it necessary to save it with an extension .c or .cpp?
I tried this on gcc but it does not compile a file with an extension other than .c and .cpp!!
| The compiler won't guess the language of the code in a file by looking at the text - you have to tell it what to compile as. Nearly every compiler allows this to be passed as a flag or it will infer it from the file extension. You're quite free to compile a .cpp file as pure C by passing the appropriate flag to your co... |
7,059,942 | 7,060,391 | Looking for C/C++ library calculating max of Gaussian curve using discrete values | I have some discrete values and assumption, that these values lie on a Gaussian curve.
There should be an algorithm for max-calculation using only 3 discrete values.
Do you know any library or code in C/C++ implementing this calculation?
Thank you!
P.S.:
The original task is auto-focus implementation. I move a (microsc... | You have three points that are supposed to be on a Gaussian curve; this means that they lie on the function:
If you take the logarithm of this function, you get:
which is just a simple 2nd grade polynomial, i.e. a parabola with a vertical axis of simmetry:
with
So, if you know the three coefficients of the parabola... |
7,060,091 | 7,060,128 | How long does SHA-1 take to create hashes? | Roughly how long, and how much processing power is required to create SHA-1 hashes of data? Does this differ a lot depending on the original data size? Would generating the hash of a standard HTML file take significantly longer than the string "blah"? How would C++, Java, and PHP compare in speed?
| You've asked a lot of questions, so hopefully I can try to answer each one in turn.
SHA-1 (and many other hashes designed to be cryptographically strong) are based on repeated application of an encryption or decryption routine to fixed-sized blocks of data. Consequently, when computing a hash value of a long string, t... |
7,060,099 | 29,366,306 | How to call constructor in gdb for pretty-printers | When debugging with GDB I would like to set a convenience variable to a newly constructed value.
I am programming using the Qt framework, so i would like to create a QString, but this is irrelevant to the question, since I would like to know how to do this with any class.
I tried
(gdb) set $str = 'QString::QString("abc... | I do not know how to free the pointer. It seems to be impossible, but the memory leak created should be quite small. But I know how to remove the effect you described as
The pointer still seems valid, which may of course be perfectly fine, since the memory has not been reused. However I am unsure whether this is okay ... |
7,060,411 | 7,060,454 | incompatible types in assignment of ‘float’ to ‘float [16]’ | I have struct:
struct mat4 {
float m[16];
mat4();
...
float *getFloat();
}
float *mat4::getFloat() {
return m;
}
Now I want to make m equal to m from newly created matrix r:
void mat4::rotate(vec3 v) {
mat4 r, rx, ry, rz;
...
matrix calculations
...
m = *r.getFloat();
}
But th... | r.getFloat() is returning a pointer to a single float. This is dereferenced to give a single float, and then assigned to an array of 16 floats.
Assuming that m contains the entire state of mat4, you can use the built in assignment operator:
*this = r;
The compiler will automatically implement the struct dump/ memcpy ... |
7,060,466 | 7,060,479 | Using smart_pointer and set_new_handler together | Do one need to worry about using set_new_handlers in conjunction with smart or auto pointer's or the libraries come packed with handlers with refined error handling?
Thanks
| The smart pointers that come with C++ (currently just auto_ptr, but soon including shared_ptr and weak_ptr) all use new by default, so they'll interface with the global new handler automatically. You don't need to do anything special to ensure that the new handler is invoked when using these classes.
Hope this helps!
|
7,060,534 | 7,060,600 | A scrollbar event when scrolling? | I need an event for detecting if an user has moved the scrollbar position to another one.
In other words, if the user does scroll up/down, would it be possible to catch a signal so I can know the scroll has been changed its position?
I think it's not important, but the scrollbar I refer to is inside a QGraphicsView.
Re... | Sliders have a sliderMoved(int value) signal, where value is the new position of slider.
|
7,060,862 | 7,081,701 | Converting Qt compliant C++ to ui XML(QtDesigner) format: | I have C++ widget code that was generated by QtDesigner (Qt open source v 4.7.3, using the Form->View Code menu in QtDesigner).
I have modified that code in a manner that is entirely Qt compliant - just hand coded a few more signals, slots and wigdets based on the patterns of the generated code - code runs perfectly w... | The c++ is a really complex language to parse, so it would be really hard / long / expensive to develop such a tool I guess.
The general rule is to never modify generated code ( in your case the code is generated by Qt designer)
You can
Subclass the generated class and put your modifications in the sub class
Code all... |
7,060,912 | 7,062,502 | Porting C++ code from MS Visual Studio to Linux and dealing with typed enums | I am porting code that was written with MS Visual Studio. For enums MS Visual Studio allows a user to specify a type like this:
enum SystemStatus : BYTE { Ok = 0, NeedsAttention, Failed };
where BYTE is unsigned char
Reference http://msdn.microsoft.com/en-us/library/2dzy4k6e.aspx
This causes errors when I try and comp... | The version of g++ you are using doesn't support c++11 features, such as extended enums. Just compile latest g++ from source, there is a helper script that downloads gcc dependencies and builds it for you.
|
7,060,930 | 7,060,959 | Is it legal to define duplicated exception specification | void FooThrow() throw(string, string)
{
}
I have compiled the above code in g++ 4.4.3 without any errors.
However, I am not sure whether or not this is a legal syntax based on the standard.
| In C++03, 15.4.6:
An exception-specification can include the same type more than once [...] even though doing so is redundant.
The standard always speaks of the set of types in an exception specification, surely that's deliberate.
I would be negligent to omit pointing out Herb Sutter's article, which is best summariz... |
7,061,005 | 7,072,733 | Microsoft Detour - Hook Function with an assembler "call" instruction | The first question on this board and already a pretty long one - i'm sorry for that (and hereby thank you all for the great tips i got from this platform).
I'm trying to hook several functions (it's more or less plugin code, so the function I want to hook is not written/can not be changed by me, but can be directly acc... | The original code performs
045A1A89 call 045A1A8E
045A1A8E pop eax
which is just an easy way to get the content of the eip register. The pop eax immediately removes the return address (045A1A8E) from the stack and sets eax to eip's value at the point of its execution.
Detours obviously has no way... |
7,061,057 | 7,061,114 | How to use my own GObject instace with C++ programs | i would like to know how i can use my own created GObject objects with my c++ code.
I have a simple libary compiled in C that define a GObject object, i would like to use this object defined there in my c++ code.
I have seen some example here
http://developer.gnome.org/gtkmm-tutorial/3.0/sec-basics-gobj-and-wrap.html.e... | You can always extend their GObject class and use that as a wrapper but the thing is that the GTK+ library uses the GObject internally I don't know why you would want to replace it (and it might complain that you've redefined a symbol somewhere or won't let you call any methods using your custom object as a parameter a... |
7,061,125 | 7,061,197 | Two files include each other in c++ problem | I'm doing some contribution to an open source library, but I'm having trouble modifying other people's code. Previously the library had a file called IntervalT.h and a file called Curves.h with the implementation in the file Curves.tcc, and Interval.h includes Curves.h for some reason. Right now I need to use IntervalT... | I can only guess (because you can name your files whatever you want), but the .tcc extension is a modification of the .cc extension (which is just C++ code) but the t stands for template. This is confirmed by the fact that Curves.h includes Curves.tcc which is a common technique for separating the interface from the im... |
7,061,345 | 7,061,367 | Using a different base constructor for a derived class C++ | From my understanding the following code will execute in this order:
Derived constructor is called.
Base object is constructed using the default base constructor.
Body of the derived constructor executes.
If so, isn't the member z is assigned a value twice?
class base {
public:
int x, y, z;
base() {x = 0; y =... | Yes, z is assigned twice in your example, just what it looks like.
To do what you're wanting, you could do something like this, which requires almost exactly the same amount of code (just moving some here and there):
class base {
public:
int x, y, z;
base(int z = 0) : x(), y(), z(z) { }
};
class derived : publ... |
7,061,416 | 7,062,403 | QMetaType and inheritance | OK, so I'm new to both Qt and C++ for that matter. I'm trying to use QMetaType with my own classes, and I can't get it to work with subclasses. Here's what I have (there're probably tons of problems, sorry):
testparent.h:
#include <QMetaType>
class TestParent
{
public:
TestParent();
~TestParent();
TestPare... | Type has to be registered! Macro Q_DECLARE_METATYPE is not sufficient.
You are missing one line at start of main function:
qRegisterMetaType<Test1>("Test1");
now you can get id that is not zero (which means that type is registered):
int id = QMetaType::type("Test1");
|
7,061,449 | 7,061,549 | What is a 'shebang' line? | Currently I'm trying to start programming on my new Mac. I installed TextWrangler, and chose C++ as my language of choice; since I have some prior knowledge of it, from when I used Windows.
So, I wrote the ever so common "Hello World" program. Although, when I tried to run it, I got an error:
"This file doesn’t app... | It does appear that you are trying to run the source file directly, however you will need to compile using a C++ compiler, such as that included in the gcc (GNU Compiler Collection) which contains the C++ compiler g++ for the Mac. It is not included with the Mac, you have to download it first:
from http://www.tech-reci... |
7,061,509 | 7,061,691 | C++ CLR win32 or others? | I am working with C++ and found that there are different kinds of C++ such as CLR, Win32, MFC....
Besides, I found that some C++ library cab be called inside some other C# program. How can it be?
Since it is believed that C++ is faster than C# as it doesn't require a platform to run it, however, if using C++ in CLR, wi... | Your confusion is understandable, but your understanding is flawed.
There's no difference between C++ and using MFC, MFC is a class framework written in C++, just like any other code you might write in C++. It's just a framework that Microsoft provides with their product.
C++/CLI (not CLR) is not really C++. It's a C... |
7,061,627 | 7,061,725 | How can I specify an array at runtime? | What I'm Trying To Do
Basically, I've got several possible arrays that I define with macros:
#define ARRAY_ONE {0, 2, 7, 8}
#define ARRAY_TWO {3, 6, 9, 2}
#define ARRAY_THREE {3, 6, 4, 5}
//etc...
At runtime, I have a C-Array that gets used in a lot of places in a certain class. I want this array to use one of the ... | I don't think that C arrays can be initialized using the curly-brace syntax after they've been declared. You can only do that when initializing them while declaring them.
Try adjusting the previously posted answer with:
const int ARRAY_ONE[] = {0, 2, 7, 8};
const int ARRAY_TWO[] = {3, 6, 9, 2};
const int ARRAY_THREE[] ... |
7,061,786 | 7,061,834 | C++ - How do i link a C++ resource? | I need to use functions in a compiled C++ resource i have.
How can i use the functions in the compiled resource and have the main program use this library i have?
I have this code:
log("INFO","THIS IS A TEST MESSAGE");
That should pull the function from the file i have. This
| Update (old answer removed)
Since you have elaborated on the need to load pre-compiled code in through "plugins". This is typically done through a mechanism known as "dynamic loading". In Windows, this is accomplished through the use of DLL (Dynamic Link Libraries) files. DLL files are libraries of compiled code tha... |
7,061,858 | 7,061,884 | Select which Webcam to use in OpenCV | I have a built in webcam (HP) and an USB webcam. Whenever I use webcams in OpenCV, the built in webcam is used. However I want use the USB webcam. I tried disabling the built in webcam and even uninstalling the drivers, but after doing that, I get a message saying that no webcams were detected, even though the USB webc... | The command CaptureFromCAM accepts an integer as its only argument which specifies the device number to use. Change this number and it will use a different device.
|
7,061,885 | 7,061,920 | C++, fastest STL container for recursively doing { delete[begin], insert[end], and summing entire array contents} | I have some code and an array where each iteration I delete the first element, add an element at the end, and then sum the contents of the array. Naturally, the array stays the same size. I have tried using both vector and list, but both seem pretty slow.
int length = 400;
vector <int> v_int(length, z);
list <int>... | Efficient additions and deletions of end elements in a container is what the deque was made for.
If you are just inserting at one end and deleting at the other then you can use a queue
|
7,061,899 | 7,061,958 | Problems pertaining to compilation of C++ application in g++ (probable cause #ifndef) | I am trying to build a Linked list application using C++ programming language & features such as inheritance etc.
I have split the interface & implementation in different files but not able to compile.
Below are the list of files
Interface files :- node.h , abstractList.h , singleLinkedList.h
Implementation files: si... | delete is a keyword in C++, you can't use it as a method name. You need to use a different name here:
class abstractList {
public:
//...
virtual void delete(const int& ) = 0;
//-----------^^^^^^ rename this.
};
|
7,062,113 | 7,062,123 | conversion from 'KanjiCard*' to non-scalar type 'KanjiCard' requested (custom enum) | Okay, I've tried using Google-sensei and searching around on this website, and while I've found many posts about this error, I haven't found any that have addressed enums. Also, all the ones I have seen have either been someone trying to assign one type to another, improper use of 'new', etc. As far as I can tell, that... | It's not cardType that's the problem; it's currentCard. You wrote this:
KanjiCard currentCard = new KanjiCard(...
That's assigning a pointer to a non-pointer type. You may have meant this:
KanjiCard *currentCard = new KanjiCard(...
...or you may have meant this:
KanjiCard currentCard(...
The former of my suggestions... |
7,062,191 | 7,062,202 | Why does the program who has a embeded manifest with CRT version 30729.4148 runs with 30729.6161(latest) in winsxs folder on runtime? | I have a question really really wondering.
I installed various versions of visual studio 2008 redistribution package in my machine.
Now, 30729.6161 is up to date.
In this environment, I made a simple program with embeded manifest which only refer to 30729.4148 CRT runtime library.
But, when I ran the program, this has... | The new runtime comes with policy files that redirects clients with older versions to the newer version.
See:
%WinDir%\WinSxS\Policies
|
7,062,442 | 7,062,457 | Largest Prime Factor- C++ | I'm trying to find the largest prime factor of the number 600851475143. My code works for smaller numbers that I test (below 100). However when confronted with 600851475143, it returns 4370432, definitely not prime. Any ideas what could be wrong with my code?
#include <iostream>
#include <time.h>
#include <math.h>
usi... | num = 600851475143;
Integer overflow occurs here. The size of num is not large enough to contain the value which you've provided.
Use uint64_t.
#include <cstdint> //must include this!
uint64_t num = 600851475143;
Read this : cstdint
|
7,062,613 | 7,062,644 | Getting function pointers from specific files | I have a lot (perhaps hundreds) of different c++ files. Each one contains 10 functions, all of them taking in an int and a double and returning an int.
So the pointer to one of these functions in one of these files would look like this:
int (*foo)(int, double);
And then I have a class, which contains 10 of these func... |
Is there any way to do this? Is there any better solution that I'm
just not thinking of?
You could just use different namespaces for them I think ? I mean each group of 10 functions in their own namespace; that way they won't conflict any more.
Other than that, you could try some dlsym + dlopen weirdness (or their ... |
7,062,735 | 7,062,798 | Access violation on destruction of a null pointer | The problem I am having is that when my class CLimb runs its destructor, if member *parent is NULL I get an "Access violation writing location 0xcccccccc" error, after the destructor is called, but before the body is executed.
limb.h
class CLimb
{
public:
CLimb(void);
CLimb(CLimb *_parent);
~CLimb(void);
... | Smart pointers are a solution. In particular, you can use a weak pointer here. A weak pointer is automatically reset when the reference count of the pointed-to object drops to zero (i.e. when it's deleted).
|
7,062,804 | 7,062,980 | Minimal Windowless OpenGL Context Initialization | How can I initialize a windowless OpenGL context with the minimal amount of code?
I've read here that you can use wglCreateContextAttribsARB to create windowless context, however it doesn't explain how?
| From the link:
Creating a context without a window, for off-screen rendering. This may not actually work.
That second sentence is important. From the WGL_ARB_create_context specification:
4) Should there be a way to make a context current without binding
it to a window system drawable at the same time?
RESOLVE... |
7,062,853 | 7,062,888 | C++ pointer assignment | Why is 90 the output value of y and q? I just do p=q. How come the value of q is changed?
int main()
{
int x;
int y;
int *p = &x;
int *q = &y;
x = 35;
y = 46;
p = q;
*p = 90;
cout << x << " " << y << endl;
cout << *p << " " << *q << endl;
cout << "Address of p = " << p ... | I'd like to share a general technique that I used to learn how pointers work when I was starting out. If you apply it to your problem, you'll see the answer as plain as day.
Get a big sheet of graph paper and lay it lengthwise on the table in front of you. This is your computer's memory. Each box represents one byte. P... |
7,062,953 | 7,063,013 | How to paint with QPainter only after a specific event? | I have a main window with some widgets on it, each needs its own graphic. I would like to use QPainter to draw shapes, lines, etc. on them, but only after a specific event, like the press of a button.
The problem is, if I just create a QPainter in any function, it won't work:
QPainter::setPen: Painter not active
The Q... | You can use custom widgets in the designer: Creating Custom Widgets for Qt Designer.
Qt Designer's plugin-based architecture allows user-defined and third party custom widgets to be edited just like you do with standard Qt widgets.
For your second question, one of the approaches is to create a QPixmap for each of yo... |
7,062,967 | 7,063,071 | Error handling design problem on collection of items | I have a collection of some items and some operation on them. This operation is a part of remote calls between client and server and it should run on all items at once. On server side it runs repeatedly on each item and may fail or succeed. I need to know which items succeeded and which failed. I guess this is rather c... |
it should run on all items at once
You will hate your life if you don't read into this as a design requirement. All or nothing is the right way to handle it. It will simplify everything you do.
If that isn't an option, just do the dumbest thing possible. Wrap each call in a try/catch and give some report. Chances... |
7,062,984 | 7,063,004 | Getting timezone in Windows with C++ | I want to synchronize Windows and Linux clocks. Windows gets its system clock (with GetSystemTimeAsFileTime function) and sends it to Linux. Then, Linux sets its clock accordingly (with settimeofday function).
I also need to transmit the time zone of Windows, and convert it to Linux standard. How can I get the timezone... | GetTimeZoneInformation is probably what you're looking for.
|
7,063,091 | 7,063,160 | Does C++ deprecate some parts of the Linux API? | I am in the middle of reading The Linux Programming Interface and Linux programming by examples. Both are very good books and explain Linux API very well. But quite often I find myself thinking that in real world projects I would prefer C++ standard library, Boost or some other good C++ library (there are many well wri... | This is not new to C++. In C, there have been two ways to open files for a long, long time:
// Only on POSIX
int fdes = open("file.txt", O_RDONLY);
Or:
// Any hosted C environment, POSIX or otherwise
FILE *fp = fopen("file.txt", "rb");
So why would anyone ever use the POSIX-specific version? The answer is simple --... |
7,063,180 | 7,063,242 | why do we need to call these functions at run time using function pointers. we can as well call them directly | Having read a bit about function pointers and callbacks, I fail to understand the basic purpose of it. To me it just looks like instead of calling the function directly we use the pointer to that function to invoke it. Can anybody please explain me callbacks and function pointers? How come the callback takes place when... | What is a Callbak function?
In simple terms, a Callback function is one that is not called explicitly by the programmer. Instead, there is some mechanism that continually waits for events to occur, and it will call selected functions in response to particular events.
This mechanism is typically used when a oper... |
7,063,185 | 7,063,301 | Some troubles with C++ template pointer-to-member based property realization | My target was to make properties in C++ like in C# - with non-trivial set/get behavior.
Here, object of Property holds refs to master of the prop and its set/get methods.
Realisation, content of Property.h:
#include <iostream>
using namespace std;
namespace First {
template <class Master, class Type>
struct ... | const Type (Master::*&get) () const;
Type (Master::*&set)(Type value);
Remove & from the above definitions. Because of &, each of these bound to the constructor parameters which do not exist after the constructor returns.
Also note that it seems that (master.*set)(value) works, its because you're unlucky. Its actually... |
7,063,265 | 7,170,563 | How to set g++ compiler flags using Rcpp and inline? | I want to set -std=c++0x, using Rcpp with inline.
I saw R: C++ Optimization flag when using the inline package but don't want to make a system-wide change, so I was trying option 2 in Dirk's answer.
I tried:
settings=getPlugin("Rcpp")
settings$Makevars[length(settings$Makevars)+1] = "CXXFLAGS = $(CXXFLAGS) -std=c++0x"
... | After some source code study, and a hint from Dirk Eddelbuettel, I've worked this out:
settings$env$PKG_CXXFLAGS='-std=c++0x'
You can set PKG_CPPFLAGS the same way.
Here is a complete and more robust example:
library(inline)
src='
using namespace Rcpp;
std::vector<const char*> test={"Hello","World","!!!"};
return wra... |
7,063,316 | 7,063,392 | GetWindowText() returning empty string and strange error | I'm using the following code inside a global CBT hook procedure:
TCHAR title[256];
int getT = GetWindowText(hWnd, title, 256);
if (getT == 0) {
int err = GetLastError();
logFile << "Error GetWindowText(): " << err << endl;
} else {
logFile << "getT = " << getT << endl;
}
The problem is that for certain win... | You might not have the rights to retrieve text from certain windows on Windows Vista and above.
My guess is that ERROR_ALREADY_EXISTS comes from your log file when you print "Error GetWindowText(): ". You should get the error code first before doing anything else.
Another possibility is that the window returns 0 from i... |
7,063,391 | 7,063,682 | How to find first non-repeating element? | How to find first non-repeating element in an array.
Provided that you can only use 1 bit for every element of the array and time complexity should be O(n) where n is length of array.
Please make sure that I somehow imposed constraint on memory requirements. It is also possible that it can not be done with just an extr... | I would say there is no comparison based algorithm, that can do it in O(n). As you have to compare the the first element of the array with all others, the 2nd with all except the first, the 3rd with all except the first = Sum i = O(n^2).
(But that does not necessarily mean that there is no faster algorithm, see sortin... |
7,063,466 | 7,064,139 | GDB keeps producing "No line xx in file" error, even though the file has the lines | This is really annoying. I got this with several files and I couldn't understand why. Here is an example source code. (Please Just don't care about the content, just copy and paste and set break point somewhere in the my_atoi function, and gdb won't allow to set the break point). my_atoi works with decimal, octal and h... | This is the 2nd case of this (or a similar) bug that I have heard of, in as many weeks,
In the first case, upgrading to 7.3 (the most recent release) fixed it also.
you should file a bug report with whomever distributes your version gdb.
you can possibly work around this by:
(gdb) maint info symtabs my_atoi.cpp
(gdb) m... |
7,063,691 | 7,063,772 | Forcing an export name for Visual Studio C++ static library | I have trouble linking a static library that is made out of a few cpp files in a project that is "pure" C .c files. The .c file is looking for a function object with syntax _FUNCTIONAME, like this:
logforwarder.obj : error LNK2001: unresolved external symbol _getEventLogProviders
but the .lib file exports it like thi... | The decoration adds both the underscore at the beginning of the exported function and the @ with the number at the end. Your .def file should therefore look like this:
getEventLogProviders=_getEventLogProviders@4
As it is now, the .def doesn't have any effect, as the mangled function is not written correctly.
|
7,063,707 | 7,063,884 | Performing STL operations on Boost::uBLAS vectors | How can I map a function to every element of a vector in uBLAS (like Map[] in Mathematica)?
For example; I want to take the sin() of all the elements of a uBLAS vector. Is there an optimized way in Boost, GSL, or any other numerical libraries to do this instead of simply looping through the elements of the vector?
Als... | Your vector (according to this) supports normal vector operations, just use the standard algorithms. In your case, here are a few of help (all inside <algorithm>):
For the sine operation, use std::transform with sinef from <cmath>
For rotation, (i'm assuming vector rotation, not angular rotation) std::rotate.
Deletin... |
7,063,984 | 7,065,016 | How to store intermediate values of circular buffer iterator? | I am a using a boost regex on a boost circular buffer and would like to "remember" positions where matches occur, what's the best way to do this? I tried the code below, but "end" seems to store the same values all the time! When I try to traverse from a previous "end" to the most recent "end" for example, it doesn't w... | This isn't quite as much an answer as an attempt to reconstruct what you're doing. I'm making a simple circular buffer initialized from a string, and I traverse regex matches through that buffer and print the matched ranges. All seems to work fine.
I would not recommend storing the ranges themselves in a circular buffe... |
7,064,039 | 7,064,062 | How to prevent non-specialized template instantiation? | I have a templated class (call it Foo) which has several specializations. I would like the compilation to fail if someone tries to use an unspecialized version of Foo.
Here is what I actually have:
template <typename Type>
class Foo
{
Foo() { cannot_instantiate_an_unspecialized_Foo(); }
// This method is NEVER def... | Just don't define the class:
template <typename Type>
class Foo;
template <>
class Foo<int> { };
int main(int argc, char *argv[])
{
Foo<int> f; // Fine, Foo<int> exists
Foo<char> fc; // Error, incomplete type
return 0;
}
Why does this work? Simply because there isn't any generic template. Declared, yes,... |
7,064,295 | 7,064,438 | RegQueryValueEx() api not providing proper set value on XP | I am trying to get a value which i had set on registry key "userpath" of type 'REG_SZ'. Simplified version of code is below.
#include <stdio.h>
#include <windows.h>
#include <iostream>
const static char* SrvKey= "System\\CurrentControlSet\\Services\\LanmanServer\\Parameters";
const static char* sVal = "I am probably \... | What does sizeof(sVal) give? 4? I'm not sure why you're using wcslen instead of strlen because sVal is a char*, not wchar_t*.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.