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,294,014 | 5,294,173 | C++ UTF-8 support on Unix / Mac OS X | I need a way to be able to read from a UTF-8 encoded file and store data from it into "UTF-8 compatible strings" of some sort, in C++. This data needs to be written back to a UTF-8 encoded file later on. There seems to be a lot of advice on google about doing this in Windows but I cannot find any help for Unix systems.... | If all you need to do is read and write it then std::string is fine.
std::ifstream fileIn("file.utf8");
std::string line;
std::getline(fileIn, line); // Reads a UTF-8 line
std::ofstream fileOut("OutFile.utf8");
fileOut << line; // Writes a line of UTF-8 text
This works because no multi-character UTF codepoin... |
5,294,018 | 5,294,108 | Serializing different data types in C++ | I have a templated container class that internally stores data in a following, static, data variable:
template<typename T>
class Container {
// ... Access methods
std::map<unsigned int, std::map<unsigned int, boost::shared_ptr<T>>
};
The first unsigned int is an id of a Client using this collection, the second uns... | You've described what Boost.Serialization does perfectly. No changes to your containers or their data types should be necessary. The library has built-in support for serializing STL containers and boost::shared_ptr already. Though you may need to add serialization methods for T depending on what it is.
|
5,294,123 | 5,294,774 | QT CMarkUp(XMLParser) error . iconv.h: no such file or director | Hi All,
I have stuck in an error for a long time and cant figure out what it is . I am using CMarkup class (xml Parser) for parsing XML files which works perfectly in VC++ . When I move that into QT it started throwing some strange error which is hard for me to fix.It says
iconv.h: no such file or director
expected; be... | If you want to add the definition to your Qt project, add this line to your .pro file:
QMAKE_CXXFLAGS += -DMARKUP_STDCONV
|
5,294,189 | 5,294,204 | c++ operator overload | //#include <string>
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
template<class T, class X> class Obj{
T my_t;
X my_x;
public:
Obj(T t, X x):my_t(t),my_x(x){}
operator T() const {return my_t;}
};
int main()
{
int iT;
Obj<int, float> O(15,10.375);
iT = O;
cou... | Yes, that is operator overloading. The operator that has been overloaded is the casting operator to type T. That's the operator that is invoked when you ask the compiler to convert an Obj<T,X> into a T.
|
5,294,278 | 5,294,296 | boost function problem | I can't figure out whats wrong with the code here, so I was hopinh someone could help me out:
In a header file, I define the following functions
void GenLiveVar(const instr_ptr instr, std::vector<ResultBase*> &list);
void KillLiveVar(const instr_ptr instr, std::vector<ResultBase*> &list);
In a class header file, I def... | The types are definitely not the same.
The argument you are passing is of type std::vector<ResultBase*>* (a pointer):
Gen(currentBlock->GetInstrPtr(i), &genList);
^
The corresponding parameter is of type std::vector<ResultBase*> (a value):
boost::function<void(instr_ptr, std::vector<R... |
5,294,331 | 5,307,279 | How to split HDF5 compund datatype in C++ | I have an HDF5 file with a compound type (int, double, double). Currently I am reading it in a single operation by storing its result in an array of structures, following the example in the documentation.
However I would prefer instead to save each of the three parts in a different array, so I would like to provide 3 p... | I don't think it is possible directly.
You can easily copy your array of structures into three arrays in a loop:
int a[n];
double b[n], c[n];
for (int i = 0; i < n; i++)
{
a[i] = s[i].a;
b[i] = s[i].b;
c[i] = s[i].c;
}
assuming s is an array of struct { int a; double b; double c; } of (constant) size n, bu... |
5,294,371 | 5,294,394 | c++ operator overload question in an interview online test | I recently saw an interview online test question that I need help with. This is not a question for a job I'm interviewing for, I was just curious about the answer. Thanks in advance.
#include <iostream>
class Foo
{
//...
};
void staff(Foo& f)
{
//..
std::out << f << endl; /... | std::ostream& operator << (std::ostream&, Foo const&);
You should define operator<< with the above signature.
|
5,294,575 | 5,294,601 | Easiest way to read a null terminate string with istream? | I have an istream and i need to read exactly a specific amount of bytes BUT i dont know the length of it. It is null terminated. I was thinking i could either 1) Write a loop and read one byte at a time 2) Tell it to return me a buffer or string which starts now until a certain byte (0 in this case). or 3) Read into a ... | Since you don't know the length of it the simplest would be:
std::string strBuf;
std::getline( istream, strBuf, '\0' );
|
5,294,585 | 5,294,599 | copy constructor in c++ | class A1{
public:
A1(){}
A1(const A1& rhs){}
void foo() {std::cout<<"Hello";}
};
class A2: public A1{
public:
A2(){}
A2(const A2& rhs){}
void foo1(A1&rhs){rhs.foo();}
void foo2(A1 a1){a1.foo();}
};
int main()
{
A2 a2;
A1 a1(a2);
a2.foo1(a1);
a2.foo2(a1);
}
How many times ... | It's much easier to talk about code that doesn't reuse variable names everywhere.
The copy constructor for A1 is called twice, and for A2 not at all.
class A1{
public:
A1(){}
A1(const A1& rhs){}
void foo() {std::cout<<"Hello";}
};
class A2: public A1{
public:
A2(){}
A2(const A2& rhs){}
void foo... |
5,294,629 | 5,294,641 | Initializing a std::vector with default constructor | I have a class field which is a std::vector. I know how many elements I want this vector to contain: N. How do I initialize the vector with N elements?
| std::vector has a constructor declared as:
vector(size_type N, const T& x = T());
You can use it to construct the std::vector containing N copies of x. The default value for x is a value initialized T (if T is a class type with a default constructor then value initialization is default construction).
It's straightfor... |
5,294,750 | 5,294,783 | Confused about an exercise in my book | I need to be able to have the objects within the array be valid or invalid/ have value or have no value.
So if the user entered only 5 accounts out of 10 possible, it would throw away the last 5 that do not have any value what so ever, so as to not ask for a computed interest for an account that doesn't exist.
How do I... | You should try tonarrow down your questions to just what you are really asking, this is a little confusing to look at.
After the first loop, have it "remember" what value for counter it managed to reach, and then in the second loop only iterate up to that, instead of up to MAX_ACCOUNTS.
And converting from months to ye... |
5,294,839 | 5,294,863 | What does " = 0" here mean? | int foo (int a , int b = 0)
I just read this code. I don't understand what " = 0" means?
I would also like to know why int foo (int a = 0, int b) does not compile.
| See
Default Argument
|
5,294,840 | 5,294,853 | return to the beginning of a pointer? | I know that you can take a pointer such as:
someFunction(const char* &txt)
{
txt++; //Increment the pointer
txt--; //Decrement the pointer
}
how do I get back to the beginning of the pointer? (without counting my number of increments and decrementing that amount) I was thinking about something like:
txt = &(*t... | You can't. You have to either save it's original position:
const char *o = txt;
// do work
txt = o;
Or use an index:
size_t i = 0;
// instead of txt++ it's i++
// and instead of *txt it's txt[i]
i = 0;
Your attempt:
txt = &(*txt[0]);
Is incorrect, if you look at it. First, it takes txt[0] (which is of type char), th... |
5,295,030 | 5,295,120 | C++ boost function issue | I did something to break the functionality in my program, but I can't figure out what. I define a typedef in a class headerfile:
typedef boost::function<void(instr_ptr, std::vector<ResultBase*>) > GenFunction;
And inside that class I have two instances:
GenFunction Gen;
GenFunction Kill
I set them as follows:
void D... | You are passing the boost::function into Set*Function by non-const reference. That prevents temporaries from being used as arguments, and the conversion from a normal function to a boost::function creates a temporary value. You will need to use a const reference for your parameter type for the code to work correctly.... |
5,295,078 | 5,295,090 | where are the non-static member variables of a class initialized? | where are the non-static member variables of a class initialized?
within the class declaration or within the constructor?? thanks
| It's within the constructor's initialization list. If a compiler-generated constructor is used then the principle is the same, it's just implicitly generated.
|
5,295,134 | 5,295,168 | Exception specification when overriding a virtual function? | If a class inherits from another and overrides a virtual function, how must the exception-specification for the derived (overridden) function be related to the base function?
Is that is must be at least as restrictive? right? or others?
| Yes, it must be at least as restrictive (§15.4/3):
If a virtual function has an exception-specification, all declarations, including the definition, of any function
that overrides that virtual function in any derived class shall only allow exceptions that are allowed by the
exception-specification of the base clas... |
5,295,159 | 5,295,170 | c++ static non-static | in c++
where are static or non-static variables stay? I mean in memory.
and, When are static or non-static variables initialized?
Need someone help me get my thought clear.
Thank you!
and what about C? same?
| They can go wherever the compiler (or linker or loader) wants to put them in memory, the C and C++ standards don't mandate that level of detail. They only mandate the behaviour.
Typically, static members are initialised once, either on program startup (including at compile time so that they're simply loaded in an alrea... |
5,295,373 | 5,295,817 | cppcheck error : Dangerous iterator usage | The code:
for(x=abc.begin();x!=abc.end();x++)
{
if(-----)
{
----
abc.erase(x);
}
}
And the error is :::
Dangerous iterator usage
After erase the iterator is invalid so dereferencing it or comparing it with another iterator is invalid.
what is the wrong usage in using erase function in ... | The itarator x is invalid after deleting the corresponding value from abc. This should fix it:
x = abc.begin();
while(x != abc.end())
{
if (-----)
{
----
x = abc.erase(x);
// skipped only to next item
}
else
{ // skip only to next item
++x;
}
}
The erase templ... |
5,295,392 | 5,295,470 | Unexpected Integer Wrapping | I am having an issue with an integer wrapping around to its minimum value unexpectedly.
The value of the integer is 15 before it wraps to -858993460.
Here is the code that is causing this issue:
while(ArrayLocation2 < EmpArray2Size)
{
GivenEmployees[(*EmployeeSize++)] = curr2;
prev2 = curr2;
if(ArrayLocati... | The expression *EmployeeSize++ returns the value pointed to by EmployeeSize and then increments the pointer, not the pointed-to item. Try (*EmployeeSize)++.
|
5,295,502 | 5,295,575 | Problem with drawing same card in poker C++ | I am trying to create a poker game with 2 players, each get 5 cards. The issue I am having is that when the first player draws his 5 cards, the second player draws the same 5 cards too. in Deck, there's a variable top_card that decrements every time for a draw. but it resets back to 51 rather then continuing from 46. C... | You pass your deck in by value, so the hand decrements the top_card variable for a copy of the deck. Pass it in by reference.
hand(deck & a) { <-- CHANGE HERE
for(int i=0;i<5;i++)
hands[i] = a.draw();
}
|
5,295,605 | 5,295,753 | winapi - Get and/or Change my hook's order and priority | my name is Dylan Michaels.
I've created a low-level mouse hook in my Win32 C++ program and I'm aware that many applications can have hooks and Microsoft Windows sends the messages to these hooks one at a time, like a chain. I want to know if I can get my hook's place in this chain and maybe even alter it.
Thanks in adv... | The API does not expose any way to determine your hook's position within the chain, and no way to alter the ordering of the chain other than when calling SetWindowsHookEx().
|
5,295,616 | 5,295,686 | How to deallocate object pointer in vector? | I have ;
class object {
// any private datas token in heap area
public :
~object () ;
};
in function ;
vector < object*> tmp ;
my question is ;
How can I erase/deallocate tmp[i] ? In other words, what things should I write in object::destructor ?
| You seem to be a bit confused. There are two concepts at play here:
How do I, the owner of tmp, deallocate the objects referred to by the pointers within tmp?
What should the destructor for the object class (~object) do?
These are not really that related. When you are finished with the tmp vector, you must manually g... |
5,295,668 | 5,697,994 | How can i get the listing of files and directories of a path using C++? | I am using the directory class to get this information but unable to assign this data to a data member of my own class. i am doing an oop project. Furthermore,I want to use the concept of Dynamism(containment).I have created two class, mydirectory and myfiles as under:
class files
{
string fname[25];
public:
fi... | Finally I completed the short project.To get the list of files and sub directories, I made use of .NET Framework namespace "System".It has got classes like "FileInfo" and "DirectoryInfo"(both belong to System::IO) which do the above required task.But here,all the string related stuff is of System::String , not of std::... |
5,296,266 | 5,296,308 | Can you please Explain the output and point out mistake | char FramebufferUpdateRequest[11];
uint16_t val;
memset(FramebufferUpdateRequest, 0, 10);
FramebufferUpdateRequest[0] = 3;
FramebufferUpdateRequest[1] = 1;
val = 3;
memcpy(FramebufferUpdateRequest+6, &val, 2);
val = 2;
memcpy(FramebufferUpdateRequest+8, &val, 2);
FramebufferUpdateRequest[10]='\0';
printf("framerequest ... | I think you wanted to write:
memset(FramebufferUpdateRequest, 0, 10);
FramebufferUpdateRequest[0] = '3'; //notice the difference
FramebufferUpdateRequest[1] = '1'; //notice the difference
val = '3'; //or var = ('3' << 1 | '3') if you want both bytes to have '3'
memcpy(FramebufferUpdateRequest+6, &val, 2);
val = '2'; ... |
5,296,311 | 5,296,346 | Listening UDP and monitoring | I have already created a UDP socket (UDP has been bound) and now i wanted the server to listen and if any client tries to connect, the listening UDP will then accept and pass the socket to a new thread to perform recvfrom and sento operation.
So how am I going to do that? How the client tells the server that he wanted ... | UDP is a connectionless protocol. You don't need to connect an udp socket. Pay attention that use a connect on an UDP socket may have a different semantic respect what you are expecting: on linux for example a connect invoked on a UDP socket , "bind" that socket to a specific IP address, but this is only a local bindin... |
5,296,484 | 5,296,580 | What are 'aliased' stream buffers? | What are 'aliased stream buffers`? I encountered the term in a comment on an answer of mine.
| I've never heard the term before, but in the thread you cite,
the person who used it also gave an example: two streams which
use the same streambuf.
Of course, just because two streams don't use the same
streambuf, doesn't mean that data written to them doesn't
ultimately end up in the same place; that they don't alias... |
5,296,572 | 5,297,559 | creating a non-uniform, integer distribution using tr1 <random> | Right now I use the following code to create a uniform distribution of integers with a range. (I took out the seeding code)
int random(int min, int max)
{
static std::mt19937 gen;
std::uniform_int<int> dist(min, max);
return dist(gen);
}
I am trying to modify it to give a distribution that favors twords t... | There are other integer distributions there, they just don't have int in their names. They do have typedef IntType result_type in their class definitions.
The ones which behave as you describe are:
binomial_distribution(t, p)
This generates numbers in the range 0 ≤ x ≤ t, so you need to translate the range by min. The... |
5,296,765 | 5,296,816 | How to know when function has to be virtual? | While describing a class, how to know when function has to be virtual?
I know what virtual function means, but I just can't figure out when I should make them virtual
Thanks
| Functions should be virtual if you want to invoke them polymorphically. In other words, virtual function express behavior that can be customized in subclasses. For instance, consider the following class:
class Car {
public:
const std::string & getId() const;
virtual void startEngine() = 0;
private:
std::str... |
5,296,870 | 5,298,919 | MFC limit selected item in ClistCtrl | Hi
I use ClistCtrl that have 20 items and I want to limit selected item number.
for example only 10 item can be selected.
how i can do it?
thanks for your help herzl.
| You would have to handle the LVN_ODSTATECHANGED notification message and count the number of selected item each time the LVIS_SELECTED state changes
Thanks
|
5,296,990 | 5,297,163 | QueryPerformanceCounter and overflows | I'm using QueryPerformanceCounter to do some timing in my application. However, after running it for a few days the application seems to stop functioning properly. If I simply restart the application it starts working again. This makes me a believe I have an overflow problem in my timing code.
// Author: Ryan M. Geiss
... | QueryPerformanceCounter is notorious for its unreliability. It's fine to use for individual short-interval timing, if you're prepared to handle abnormal results. It is not exact - It's typically based on the PCI bus frequency, and a heavily loaded bus can lead to lost ticks.
GetTickCount is actually more stable, and ca... |
5,297,185 | 5,297,260 | Simpliest RPC in Java and C++ | I'm looking for a very simple way to allow RPC between Java and C++ applications.
My system contains several Java modules and one C++ module.
I have not too much different procedures to call (about 2-3 per module), and they will not change much (except some minor adaptations like adding a new procedure or changing one... | I don't know if either one would meet your criteria for simplicity, but I'd say your two best bets are something old - CORBA - and something new - web services.
CORBA comes to mind because interoperation of distributed components written in different languages was part of its inspiration, but it's not simple. The mark... |
5,297,477 | 5,297,632 | operator overloading in c++ | suppose i have 2 objects of a class and it has one int data member.
i want to add those integer data to other object and store the output in the first obj's data member.I can overload the + operator and use the statement like below
X+Y //where X and Y are objects of one class.
if i have to add like below
X+10// here... | The same way:
MyClass operator+(MyClass const& lhs, MyClass const& rhs);
MyClass operator+(MyClass const& lhs, int rhs);
MyClass operator+(int lhs, MyClass const& rhs);
(operator+ should not normally be a member.)
If you overload operator+, you'll also want to overload +=. One
frequent idiom involved implementing + i... |
5,297,763 | 5,297,898 | GCC's two unusual error messages | Today, I came across two error messages which I never seen before. It's completely new to me.
Here is the code:
template<typename T>
struct adder { adder(const T &item) { } };
template<typename T>
void initializer(const T &item) { adder<T>(item); }
int main()
{
initializer("const string literal");
}
On compilin... | The key to understanding what is happening is to realize that:
adder(item);
is a definition of a local variable named item and having type
adder; the parentheses are superfluous, but perfectly
permissable. If you want to call the constructor, you'll have
to disambiguate, by writing it in some way that cannot be
in... |
5,297,892 | 5,297,998 | Executing another program from C++ with specified running timeout | I'm writing a program (A genetic algorithm implementation) which executes another program using "system" method to calculate fitness. The problem is that another program sometimes hangs for unlimited amount of time. How can I execute a program with some time limit from C++.
Both POSIX and c++ solutions are appreciated.... | Instead of system, execute the program with the fork/exec idiom. Before the exec, set RLIMIT_CPU to a maximum value with setrlimit in the child.
Make sure the child does not ignore SIGXCPU (which is very unlikely).
|
5,297,936 | 5,309,075 | Crashes during UnhookWindowsHookEx() | I made hook for calculator and want to get messages which calculator receives. To do that, I set my own window procedure, but during unhooking if I use SetWindowLong(..) to recover the old window procedure program crushes.
DLL code:
#define EXPORT_API extern "C" __declspec(dllexport)
EXPORT_API void InstallHook();
EXP... | The problem is that you are setting the window proc on the target window from within the target process (calc), and in that case, it is succeeding. But when you call UninstallHook, that code runs in your own exe's process; and in that case, SetWindowLong will fail.
(Putting the hook values in shared memory won't help; ... |
5,297,994 | 5,298,204 | How read from multiple pipes in Windows in same thread | In my program I have saveral pipes which are connected to stdout and stderr streams of child processes (i.e. in main process I'm reading from this streams). But when there is nothing to read from one of them my program hangs. Is there way to solve this problem not using thread. Also I want all child processes to be kil... | You can use a similar approach in windows. Using OVERLAPPED structs, you can issue asynchronous I/O against the pipes. Then use WaitForMultipleObjects on the associated event handles with a timeout (this is the select analog). See this for an overview of the options.
|
5,298,040 | 5,301,071 | Can I do this with regex? | I need a rule that regex or similar that can be used to parse any given input string containing space delimited words to create a usually longer output string where certain parts get expanded according to certain conditions. I could create code to do this from scratch but I was wondering if I might not need to as this ... | Regex is probbably not helpfull, others may be helpfull but most of the work would still need to be done yourself.
|
5,298,051 | 5,298,365 | C++ STL unordered_map iterator problem | class Demo {
struct FileData {
int size;
BYTE* buffer;
DWORD flags;
};
typedef std::tr1::unordered_map<std::wstring,FileData> FileMap;
FileMap m_fileMap;
void myFunc()
{
std::wstring name = L"TestFile.png";
FileMap::const_iterator iter = m_fileMap.find(name);
... | iterators are assignable and whilst keys and values in maps must be copyable, they do not need to be assignable.
Therefore it cannot use a copy in the general case, it must hold a pointer or reference internally.
In some cases eg ints it might specialise and use copies anyway.
|
5,298,059 | 5,298,270 | How to manage SFML rendering, the "signals" way? | I'm developing a little snake game written in C++ and using SFML 2D library. The problem is: in order to render a window, and to print anything in it, you have to make it through a
while (App->IsOpened())
{
//Do the stuff
App->Clear();
App->Display();
}
But, I'd like to build my program in a more generic ... | There's no need to send such signals. Everything should be handled in that while loop (the main loop), and every frame should be cleared, and drawn individually and as a whole, not in regions, hence SFML uses OpenGL.
The most obvious way to separate the game logic from the main loop is making the game OOP.
Of course, i... |
5,298,125 | 5,298,765 | cmake shared libraries | I'm building app with boost.python. I want to make each cpp-module as a single shared library.
I have a list of cpp-files, how to make in cycle different subprojects with name taken from cpp file?
For example:
set(Script_srcs
Module1.cpp
Module2.cpp
Module3.cpp
)
some_cycle
add_library( {NAME} SHARED {PA... | You could use foreach to iterate over your source-files and use a the function get_filename_component with NAME_WE to get only the filename, something like:
set(Script_srcs Module1.cpp Module2.cpp Module3.cpp )
foreach( f ${Script_srcs} )
get_filename_component( ff ${f} NAME_WE )
add_library( ${ff} SHARED ${f}... |
5,298,268 | 5,298,344 | Returning a string from PInvoke? | I am using PInvoke for interoperability between Native Code (C++) and Managed Code (C#).
I just write a simple function which gets a string from C++ code. My code looks like
C# Code:
[DllImport("MyDll.dll")]
private static extern string GetSomeText();
public static string GetAllValidProjects() {
string s = GetSome... | First of all, as others have pointed out, your C++ is broken even before trying interop. You are returning a pointer to stri's buffer. But because stri is destroyed as soon as the function returns, the return value is not valid.
What's more, even if you fixed this, you need to do more. It won't work allocating memory i... |
5,298,394 | 5,298,419 | How to declare an __stdcall function pointer | I tried this
typedef void (* __stdcall MessageHandler)(const Task*);
This compiles but gives me this warning (VS2003):
warning C4229: anachronism used :
modifiers on data are ignored
I want to declare a pointer to a function with stdcall calling convention? What am I doing wrong?
| As MSDN says, the correct way to write this is
typedef void (__stdcall *MessageHandler)(const Task*);
|
5,298,421 | 5,298,459 | Why doesn't java support pass by reference like C++ | I have read every where that primitive datatype and object references are passed by value?
I have tried searching in Google why doesn't java support pass by reference , but I only get java does not support pass by reference and I couldn't find any reason behind it.
Why can't you pass primitive datatype by reference ?
E... | By design:
Some people will say incorrectly that
objects are passed "by reference." In
programming language design, the term
pass by reference properly means that
when an argument is passed to a
function, the invoked function gets a
reference to the original value, not a
copy of its value. If the functio... |
5,298,466 | 5,298,586 | Prevent two classes from inheriting from a base class with same template arguments | I have a class that is suppose to be a base class:
template<int ID>
class BaseClass { ... };
How can I make a compile-time error appear if two classes try to inherit form this base class using the same value of ID. That is - this code is suppose to work:
class A : BaseClass<1> { ... }
class B : BaseClass<2> { ... }
B... | I think that is impossible.
If it were possible, then we can make compiler to generate error for the following code as well, which is conceptually equivalent to your code.
struct Base {};
struct OtherBase {};
struct A : Base {}; //Base is used here!
struct B : Base {}; // error - used base class. please use some other... |
5,298,917 | 5,299,488 | C++: Optimizing a simple image clipping operation... too many if() statements | The code I have here is preliminary. I am focusing on the clipping procedures. There seems to be a lot of if() statements, and I'm hoping someone will have a clever way of optimizing this at least a little bit.
If you're wondering what m_nStride is, it's the number of elements to add to any given pixel pointer to reach... | For performance, the if overhead is virtually zero compared to the for loops. Nonetheless, as an exercise here's a version with fewer checks. It clips the bounds first and then only needs to check width and height being positive.
void Image::Clear(int nLeft, int nTop, int nWidth, int nHeight, DWORD dwColor)
{
if(nL... |
5,299,095 | 5,299,189 | Static initialization order fiasco | In his "Thinking in C++" (Chapter 10) Eckel describes a technique that was pioneered by Jerry Schwarz to solve the fiasco.
He says that if we want to initialize x to 100 and y to 200 and share them among all translation units, we create an Initializer.h that looks like this:
extern int x;
extern int y;
class Initializ... |
But if it is true, and the compiler handles the implementation file after some another file, than it will set x and y to zero eliminating initialization and all possible changes in previous files?
I'm not sure what you mean by this. If x and y are defined in other files, then you have a linker clash and the program s... |
5,299,138 | 7,386,552 | Translating a C++ API into a managed code API | I am trying to wrap a C++ library in Objective-C classes for importing into MonoTouch using btouch. I am trying to get to grips with how to translate the API for use in a managed environment. Specifically, how to handle methods that take in pointers to local variables, like the ULDatabaseManager::OpenConnection static ... | The way that I resolved this is to change the API being exposed to Monotouch with btouch. Specifically, methods such as OpenConnection I only required the connectionParms, not the pointer to the error class. I then did error checking in the open method and returned nil if an error occurred. In the wrapper class I also... |
5,299,179 | 5,299,751 | Boost python export singleton | I have a singleton (from boost::serialization):
class LogManager : public boost::serialization::singleton<LogManager> { ... };
And wrapper for getting instance:
inline LogManager &logManager() { return LogManager::get_mutable_instance(); }
What's the right way to bind this into boost.python module?
I tried:
class_< L... | In addition to using bases<...> in the second argument as Autopulated pointed out, I think you also want to specifiy boost::noncopyable as the third template argument, e.g.
bp::class_<LogManager, bp::bases<boost::serialization::singleton<LogManager> >, boost::noncopyable>("LogManager", bp::no_init)
Edit:
Also, you nee... |
5,299,306 | 5,299,375 | What is best GUI toolkit to rewrite .NET WPF application to C++? | We have existing WPF application with complicated graphics (rounded edges of the window, speedometer style indicators etc).
Since we rely on .NET our application needs .NET framework. Some users are unwilling to install .NET and we want to provide them with a version that does not need .NET and runs of Windows only (XP... | Sorry I do not have the answer to your question (and I would never ever even dream that I might do such a thing), but I am compelled to tell you as an advice
implementing all the WPF functionality in C++ will take 10-20 times more
installation of a C++ would not be necessarily easier
if you need to make installation e... |
5,299,442 | 8,645,849 | Is there a bug reporting library similar to the bug report system on Android Market? | I'm currently using Trac for bug tracking, but I'm looking for a solution to automatically catch/detect/notify remote bugs.
Is there a library/solution for a bug reporting system similar to the one available for Android developers at the Market Developer Console? Briefly, a solution that catches (Or can be programatica... | Bug4j does that.
See http://code.google.com/p/bug4j/
|
5,299,843 | 5,421,824 | The mechanics of extension via free functions or member functions | Loads of C++ libraries, the standard included, allow you to adapt your objects for use in the libraries. The choice is often between a member function or a free function in the same namespace.
I'd like to know mechanics and constructs the library code uses to dispatch a call which will call one of these "extension" fu... | Well, I can tell you how to detect the presence of member functions of a certain name (and signature) at compile time. A friend of mine describes it here:
Detecting the Existence of Member Functions at Compile-Time
However that won't get you where you want to go, because it only works for the static type. Since you wan... |
5,300,085 | 5,300,139 | Code compiles despite of taking address of Wrong Data Types | #include <iostream>
#define n 255
using namespace std;
int main()
{
int i=n;
int *ptr=&i;
int const *ptr_1=&i;
const int *ptr_2=&i;
const int * const ptr_3=&i;
}
Why does this Code Compile in Visual C++, Dev C++ and G++?
Link to - Ideone -
| It does compile, because all those pointers ether don't change const-qualification of the variable access or enforce the qualification, but none of them tries to loosen the qualification.
For example:
const int var;
int* address = &var; //illegal - tries to remove const
would try to get non-const access to a const var... |
5,300,124 | 5,300,143 | calling the default constructor | class base {
int i;
public:
base()
{
i = 10;
cout << "in the constructor" << endl;
}
};
int main()
{
base a;// here is the point of doubt
getch();
}
What is the difference between base a and base a()?
in the first case the constructor gets called but not in the second case!
| The second one is declaring a function a() that returns a base object. :-)
|
5,300,275 | 5,300,538 | Equivalent of incrementing a C/C++ pointer in Java? | I do have somewhat of a feeling that people will try to beat me over the head and say "You're not supposed to do that!" (and I'm quite aware of this fact); nevertheless, here's my problem:
Suppose you've got the following C++ code:
EDIT:
I think I haven't shown enough of what I'm trying to do, even though most of the a... | Java is not C++. The things you do in C++ to gain speed do not necessarily apply to Java. This is one of those cases.
Using the for(int val : x) in Java will not, as some people suggest, give you any advantage over:
for(int i = 0; i < x.length; i++)
{
int val = x[i];
}
Reference here; http://java.sun.com/docs/bo... |
5,300,564 | 5,300,688 | Changing the stride of a pointer increment | I currently have a class like this:
struct Rgb
{
static const int NUM_CHANNELS = 3;
unsigned char channel[NUM_CHANNELS];
};
which is never instantiated but is used to determine the stride of a pointer increment.
I wanted to allow this stride to change based on some runtime information. Will something like this wor... | As [i] is a compile-time operation, it will simply not work for element sizes that are not known at compile-time. You must increment the pointer yourself with arithmetic.
But that being said, most likely you actually know the size of the element at compile-time. You are probably writing specific code for 24-bit and 32-... |
5,300,602 | 5,300,653 | Template Return Type with Default Value | So in writing a C++ template class, I have defined a method that returns an object of the templated type, as such:
template <typename T>
class Foo
{
public:
T GetFoo()
{
T value;
//Do some stuff that might or might not set the value of 'value'
return value;
}
};
int main() {
... | Sounds OK, if the class has no copy constructor, you will not be able to return it anyway.
|
5,300,627 | 5,301,041 | What does it mean when the function in global namespace is declared as static C++? |
Possible Duplicate:
What is a “static” function?
I have seen a function in a global namespace that is declared like this:
static int function_name(int a, double* p, int c, float * u)
{
//do something with these arguments
}
What the static keyword means here?
EDIT: Now when I know what is for static, please ex... | You would use a static function with the scope in the compilation unit when you really want the function with that name to be known only inside that compilation unit. A class or function that is not in that scope cannot accidentally call the function. (I'd have put this in a comment but I don't have privileges for t... |
5,300,966 | 5,301,252 | Rationale of un-deprecating static keyword for nonmember functions |
Possible Duplicate:
Deprecation of the static keyword… no more ?
I am asking this question because of a comment on an answer of mine which states that the use of static keyword on freestanding (nonmember) functions has been un-deprecated in C++0x.
Since I have no reason to doubt the above statement, I am asking thi... | I found this in the CWG issues list:
http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#174
|
5,301,131 | 5,301,167 | Recursive templates: compilation error under g++ | I am trying to use templates recursively to define (at compile-time) a d-tuple of doubles. The code below compiles fine with Visual Studio 2010, but g++ fails and complains that it "cannot call constructor 'point<1>::point' directly".
Could anyone please shed some light on what is going on here?
Many thanks, Jo
#incl... | What are you trying to do with:
coordPointPair.second.point<N-1>::point();
It looks like you want to explicitly call the point default constructor - which has already been called when the pair was constructed. You cannot call constructors directly (unless you use placement new, which wouldn't make sense in this scenar... |
5,301,627 | 5,327,164 | std::map losing track of my data? | I'm sticking some data, wrapped with boost::any into a map in a class method getValue. Everything works fine, the data is in the map as appropriate etc etc in getValue. The second I leave getValue and try to use this data, it's no longer in the map.
This has me stumped, I'm probably forgetting to use a reference at... | I fixed this, note how I define key in getValue as being std::string(identifier). In test.c I was defining key as sanitizeString(..) which returned a different key, obviously. Of course you guys couldn't see that so my bad.
|
5,301,666 | 5,301,789 | What is the rationale for not having static constructor in C++? | What is the rationale for not having static constructor in C++?
If it were allowed, we would be initializing all the static members in it, at one place in a very organized way, as:
//illegal C++
class sample
{
public:
static int some_integer;
static std::vector<std::string> strings;
//illegal constructor!... | Using the static initialization order problem as an excuse to not introducing this feature to the language is and always has been a matter of status quo - it wasn't introduced because it wasn't introduced and people keep thinking that initialization order was a reason not to introduce it, even if the order problem has ... |
5,301,706 | 5,301,783 | Default values in templates with template arguments ( C++ ) | Assume I have a template (called ExampleTemplate) that takes two arguments: a container type (e.g. list, vector) and a contained type (e.g. float, bool, etc). Since containers are in fact templates, this template has a template param. This is what I had to write:
#include <vector>
#include <list>
using namespace std;
... | Perhaps you'd prefer this:
#include <vector>
#include <list>
using namespace std;
template <class Container>
class ForExamplePurposes {
typedef typename Container::value_type T;
Container items;
public:
};
int main()
{
ForExamplePurposes< list<int> > a;
ForExamplePurposes< vector<float> > b;
}
This ... |
5,302,076 | 5,302,490 | Python initialization segfault | I'm building app with boost.python. I have some singleton class named ScriptsManager, it has function initPython which does:
mMainModule = bp::import("__main__");
mMainNamespace = bp::import("__dict__");
bp::object ignored = bp::exec("hello = file('hello.txt', 'w')\n"
"hello.write('Hello world!')\n"
... | I think what you want is the following:
int main (int argc, char** argv)
{
try
{
// If you're going to use threads: PyEval_InitThreads();
Py_Initialize();
PySys_SetArgv(argc, argv);
bp::object mMainModule = bp::import('__main__');
bp::object mMainNamespace = mMainModule.... |
5,302,456 | 5,302,570 | How do I get the high- and low-order bits of a SHORT? | The function GetKeyState() returns a SHORT that contains the key's state (up/down in the high-order bit, and toggled in the low-order). How do I get those values?
| Simple bit manipulation will work. SHORTs are 16-bit integers, so to get the low- and high-order bits you can do the following:
lowBit = value & 1;
highBit = ((unsigned short) value) >> 15;
Also, note that the LOBYTE and HIBYTE macros are used to break SHORTs into low- and high-order bytes, not to test individual bits... |
5,302,473 | 5,302,660 | Simulate mouse move in 3D games? | Hi
I made a human computer interface to control mouse using fingers using C++ and OpenCV in CodeBlocks IDE
http://www.youtube.com/watch?v=-q5aXTg0pVE
I want to use this in a 3D game like medal of honor
First I used SetCursorPos(x,y) it did not work so I switched to SendInput and mouse_event.
They did work with a bug th... | Without seeing your code, this answer is a bit of a long shot, but here goes.
SendInput should work, but I think the game is interfering by using SetCursorPos itself. Many games reset the cursor to the centre of the screen each frame, so it doesn't hit the edge by accident.
Try using SendInput with relative mouse motio... |
5,302,767 | 5,302,898 | Confusing char arrays and pointers in c++ | Hey everyone, thanks for taking the time to address my problem. I've looked at so much material at this point that I've just started getting more and more confused. Basically, I'm writing a simple segment of code that parses a string. Please understand that my question is NOT about parsing. I am using C++ and have ... | It's not clear why you're trying to do this with '\0' terminated
strings, when C++ has a perfectly usable string class, but
supposing some pedagogical reasons: are your strings '\0'
terminated? How do you extract and copy the first x chars into
ps.chunk1? How do you ensure that it has a '\0'?
If you really want to ge... |
5,302,848 | 5,302,868 | g++ does not show a 'unused' warning | I have a little piece of code in C++:
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
int i=0;
istream_iterator<string> EOS;
double x;
return 0;
}
Now i compile it with my g++ (GCC) 4.4.4
g++ -W -Wall -pedantic test.cc -o test
And get:
test.cc: In functi... | It is not a primitive value, so its constructor and/or destructor might have desired side effects.
To illustrate that this happens in practice: I use a class to time sections of code, that looks roughly like this:
class Timed {
double start;
public:
Timed() { start = now(); }
~Timed() { std::cou... |
5,303,019 | 5,303,068 | Template functions: default construction without copy-constructing in C++ | Considering
struct C {
C() { printf("C::C()\n" ); }
C(int) { printf("C::C(int)\n" ); }
C( const C& ) { printf("copy-constructed\n"); }
};
And a template function
template< typename T > void foo(){
// default-construct a temporary variable of type T
// this is what ... | Here's a trick you can use, using a local class:
template <typename T> void foo() {
struct THolder {
T obj;
THolder() : obj() { } // value-initialize obj
};
THolder t1; // t1.obj is value-initialized
}
I think I read about this trick from an answer to another Stack Overflow question, but I... |
5,303,059 | 5,304,167 | In C/C++ I want to write to the same pipe multiple times | I have a program that creates pipes between two processes. One process constantly monitors the output of the other and when specific output is encountered it gives input through the other pipe with the write() function. The problem I am having, though is that the contents of the pipe don't go through to the other pro... | How are you reading the other end? Are you expecting complete strings? You aren't sending terminating NULs in the snippet you posted. Perhaps sending strlen(string)+1 bytes will fix it. Without seeing the code it's hard to tell.
|
5,303,205 | 5,303,281 | hash_map questions / tutorial | I know how hashmap works in Java. But I can't fully understand in C++.
I found some simple tutorials, but there are no hashfunctions etc..
Does a string need hash function?
hash_map<string, string> hm;
hm.insert(make_pair("one", "two"));
hm.insert(make_pair("three", "four"));
how will it work without hash functions fo... | For starters, hash_map is not a standard C++ library; it's a compiler extension that ships with Visual Studio and g++. If you want to use a more standardized hash table in C++, look at either the Boost.Unordered libraries, the TR1 hash containers, or, if you have a more modern compiler, the new C++0x standard hash con... |
5,303,504 | 5,303,620 | Friend functions of a class template | I have a class template Foo<T>.
I'd like to implement a non-member function Bar that takes two Foos and returns a Foo. I want Bar to be a non-member because it will be more natural for callers to write Bar(f1, f2) than f1.Bar(f2). I also want Bar to be inline because the calculation is trivial and frequent.
template ... | If the calculation is trivial, I would write:
template <typename T>
class Foo {
...
private:
T w, x, y, z;
public:
friend Foo Bar(const Foo &lhs, const Foo &rhs) {
...
}
};
This doesn't fall foul of the ODR - it's an inline function with external linkage (3.2/5 excludes this from the ODR subj... |
5,303,608 | 5,303,689 | "delete this" in constructor | What actually happen when I execute this code?
class MyClass
{
MyClass()
{
//do something
delete this;
}
}
| Note: This answer applies to C++03, and it seems like the behavior was changed in C++11 and higher so that this is now undefined behavior.
It turns out that in this particular case the code is legal, but you're ε-away from undefined behavior.
The C++03 standard defines the notion of the "lifetime" of an object to be th... |
5,303,643 | 5,305,811 | C++:Undefined reference to 'FMOD:: X' | After looking around for various sound API libraries, I have decided to use FMOD for the time being.
Problem is that whenever I try to compile one of the code examples, I get the following errors:
obj\Release\main.o:main.cpp|| undefined reference to `FMOD::System::getVersion(unsigned int*)@8'|
obj\Release\main.o:main.... | When using FMOD with Code::Blocks you need to use the C API, not the C++ API. FMOD is built with Visual Studio, therefore the C++ symbols use the VC mangling scheme. There is a note in the "Getting Started with FMOD for Windows" document that mentions this.
http://en.wikipedia.org/wiki/Name_mangling#How_different_compi... |
5,303,680 | 5,303,749 | IDE for C++ developers | What is the most popular IDE for C++? And library for windows?
What is about QT?
| The best IDE for c++ is visual studio(if you are working in windows), but if you want to use Qt, QtCreator is also nice. but i can't get what do you mean "A library for windows"!
|
5,303,722 | 5,303,770 | Destructor on const char * | In my program, i have line like this:
const char * str = getStr();
Do i need to call destructor on str [] at the end of function to prevent memory leaks?
| Question does not contain enough information to tell, it depends what getStr() does. For example:
const char *getStr() {
return "boo";
}
then you must not call delete.
const char *getStr() {
return new char;
}
then you should call delete str; to avoid a memory leak (and must not call delete[]).
const char *ge... |
5,303,741 | 5,971,347 | Best Api to unzip a file into memory | I'm working on a Qt application where we have to read in zipped files or QByteArrays and unzip them in memory, reading the file contents without actually unzipping the file to disk.
Is there a good sdk that can enable this easily? We currently use QArchive (bugless), but we have found it to anything but bugless and are... | We ended up going with quazip. Thanks Eugen.
Seems to be working well.
|
5,304,048 | 5,304,754 | STL Containers allocation placement new | I couldn't find an exact answer to this question and hence posting here.
When I think of vector, it needs to build objects in a contiguous memory location. This means that vector keeps memory allocated and have to do an in-place construction (=placement new) of objects being pushed into it. Is this a valid assumption?... |
This means that vector keeps memory allocated and have to do an in-place construction (=placement new) of objects being pushed into it. Is this a valid assumption?
Yes
Also, does this mean the container is manually invoking the destructor rather than calling delete?
Yes
Are there any other assumptions that I am mi... |
5,304,239 | 5,304,480 | Finding the largest palindrome in string implementation | I'm trying to solve a problem that asks to find the largest palindrome in a string up to 20,000 characters. I've tried to check every sub string whether it's a palindrome, that worked, but obviously was too slow. After a little googling I found this nice algorithm
http://stevekrenzel.com/articles/longest-palnidrome. I... | I can see two major errors:
Whether you initialise your upper/lower pointers to i,i or i,i+1 depends on the parity of the palindrome's length you want to find, not the original string. So (without any further optimisations) you'll need two separate loops with i going from 0 to len (len-1), one for odd palindrome lengt... |
5,304,411 | 5,304,982 | How do you get vertex buffer of mesh? | How to get vertex information of mesh?
| If you mean from an ID3DXMesh then its just a matter of calling GetVertexBuffer and GetIndexBuffer. To get additional information, such as the vertex structure, you can call GetDescription. Finally to get the information about how the mesh should be rendered (such as which verts use the same material) the information... |
5,304,515 | 5,305,005 | Test if template argument defines a specific type name | Assume I have a template class like this:
template<typename T>
class Foo {};
And a class like:
class PossibleArg
{ typedef int required_type; }
Is it possible to write a static_assert in class Foo which checks if T::required_type is defined?
| Maybe something looks like:
template <typename T>
class Foo {
static_assert(sizeof(T::required_type) > 0, "Never shows up");
};
EDIT: Other way: SFINAE
template <typename T>
struct has_required_type
{
typedef char yes[1];
typedef char no[2];
template <typename C>
static yes& test(typename C::required_type*)... |
5,304,606 | 5,304,629 | A class object to another datatype? | Can you convert a class object to for example to int, double, char etc.. is it called implicit or explicit conversion?
class MyClass
{
int x;
};
int main()
{
MyClass MyObject; //convert my object to int
}
| Create a casting operator:
class Foo {
public:
operator int() const { return 1; }
};
class Bar {
public:
operator Foo() const { return Foo(); }
};
int main() {
Foo f;
Bar b;
int i1 = f; // implicit, just one conversion
int i2 = b; // not valid
int i3 = static_cast<Foo>(b); // Convert b t... |
5,304,635 | 5,304,672 | qt to c# what does : operator mean within struct | I have a block of code that i'm trying to covert from an old qt file into C# but i'm a little unclear what is going on in the struct within the union below. I'm not sure what the ':' does... i'm guessing it sets the size but could not find any documentation on this. Also since C# does not have unions what is the bes... | This is what is called BitFields. the portion sBcdWord is a 32 bit word, and each field is a portion of that word taking respectively 8,2,18,3,1 BIT:
So the word layout is as below:
Bit0-Bit7 m_0
Bit8-Bit9 m_S
Bit10-Bit27 m_D
Bit28-Bit30 m_ss
Bit31 m_P
How to port this in C# depends if you are convettually porting th... |
5,304,636 | 5,304,699 | C opaque pointer gotchas | I'm working with a legacy C library interface (to C++) that exposes opaque pointers as
typedef void * OpaqueObject
In the library:
OpaqueObject CreateObject()
{
return new OurCppLibrary::Object();
}
This of course provides absolutely no type safety for clients of this library. Should changing the typedef from a v... | There are no gotcha's; that form is preferred exactly because of type safety.
No, alignment is not an issue here. The pointer itself has a known alignment, and the alignment of the object it will point at is only of concern to the library implementation, not the user.
|
5,305,007 | 5,305,031 | python zlib output to c++ string | I am trying to write the output of python zlib's output to a c++ string. The question is very similar to Python zlib output, how to recover out of mysql utf-8 table? here however, the difference is that my python script generates a C++ header file where the compressed data should be stored as a string. However, because... | You need to escape the non-printable characters in the string using octal notation.
For example,
import string
....
safe_string = ""
for ch in compressed_string:
if ch in string.printable and ch != '\\':
safe_string += ch
else:
safe_string += "\%o" % ord(ch)
content = ".....\"%s\" ...." % safe_string... |
5,305,010 | 5,305,060 | push_back problem on vector<vector<int> > | Dear All,
I used a vector of vector, say vector<vector<int> > no_1_2 to store elements of two vector<int> containers, say no1 & no2. so for e.g. i would say, no1={2,5,7,10,3} and no2={21,34,15}.
I wanted to store these 2 vectors in one container called no_1_2 and I used no_1_2[0].push_back(no1.at(i)) and no_1_2[1].pu... | Without seeing your actual code and errors, let me guess:
You didn't call no_1_2.resize(2) before you accessed no_1_2[0] or no_1_2[1]
EDIT: After seeing code, the above's no longer guesswork:
You cannot do no_1_2[0].push_back(*i); - no_1_2 is empty and you're trying to access no_1_2[0]. You will need to resize it befor... |
5,305,084 | 5,305,115 | memcpy of a part of a struct | I have a struct/class which is partiall Plain Old Data (POD).
struct S {
// plain-old-data structs with only arrays and members of basic types (no pointers);
Pod1 pod1;
Pod2 pod2;
Pod3 pod3;
Pod4 pod4;
vector<int> more;
};
I copy objects of class S a lot.
I would like to copy it with memcpy, but S::more pr... | The best solution is to rely on C++ automatic copy constructor and copy operator. The compiler has then a chance to understand your code and optimize it well. Try to avoid memcpy in C++ code.
If you need to copy only part of the structure, create a method for it:
struct S {
// plain-old-data structs with only arrays ... |
5,305,235 | 5,305,278 | Cannot connect to PostgreSQL using C++ | I am trying to run PostgreSQL on my mac. PostgreQL itself works fine and I can create database and table and stuff but when I try to connect to PostgreSQL using C++ with something like:
#include <stdio.h>
#include </Library/PostgreSQL/8.4/include/libpq-fe.h>
#include <string>
int main() {
PGconn *conn;
P... | g++ can't find the pq library. You have to specify where to look for it, with a capital -L:
g++ -L/path/to/pq/lib -lpq db.cpp -o db
where pq is /path/to/pq/lib/libpq.a (or whatever the extension is)
Here's what you probably want to do:
change the include line to not have the path.
#include "libpq-fe.h"
Add the inc... |
5,305,370 | 5,305,754 | SIFT, HOG and SURF c++, opencv | I have a simple question, which I want to know, what kind of libraries are available and can give good results for implementing SIFT, HOG(Histogram Oriented Gradient) and SURF in c++ or opencv?
Hence: 1- Give me the link for the code if you can, which I will be so appreciated.
2- If you know one of them or any kind of ... | check these:
surf
- great article
http://people.csail.mit.edu/kapu/papers/mar_mir08.pdf
sift
- great source, I tried it on the iPhone
http://blogs.oregonstate.edu/hess/
- fast - fast corner detection library
http://svr-www.eng.cam.ac.uk/~er258/work/fast.html
|
5,305,391 | 5,305,546 | Winsock accept() returning WSAENOTSOCK (code 10038) | hope you're having a good day. Another socket issue, another day :)
I finally got MicroSoft Visual C++ (MSVC++) IDE installed, plus the Platform SDK, so I can compile winsock applications.
Missed a chunk of stuff here. In the ServerSocket::accept() function, it creates a new instance of ClientSocket and sets it's socke... | Looks like you're not following the Rule of Three. Any time you have a destructor, you need to write or disable both the copy-constructor and assignment operator.
In your example usage:
ClientSocket client = server.accept();
The variable client is copy-constructed from the return value. Then the destructor runs on t... |
5,305,460 | 5,306,468 | Problems using Borland C++ compiler (version 5.5) | Declaration:
namespace a {
namespace b {
class Classe {
public:
Classe();
};
}
}
Definition:
#include "sample.h"
namespace a {
b::Classe::Classe(){}
}
But with this definition I got this error:
Error E2038 .\sample.cpp 4: Cannot
declare or define
'b::Classe::Clas... | Try removing the namespace block in the .cpp file, and just qualify the entire constructor:
#include "sample.h"
a::b::Classe::Classe(){}
|
5,305,663 | 5,305,702 | Hiding iteration in a function | Only got rough idea of what I want, perhaps someone could pad it out and/or tell me if its possible.
I would like to simplify my multiply nested loops, to that end I would like to be able to call a function (for example that uses boost::filesystem) that returns a file in a directory, each successive call would return t... | Create a functor: an object that is called like a function.
The object will hold the query results and the current state of the query. You define an operator() so the object can be called as if it were a function. Each time this function is called you return one result and update the object's internal state.
Example:
#... |
5,306,349 | 5,306,430 | Segmentation fault in std::string::size() const ()? | I was writing a program that tell the user to input a random string, and then print out all the duplicates and the number of time each of them repeats. I was running it through gdb and this is the output:
Here is the program:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
... | Some bugs:
if (sentence[i] == sentence[i+1]) {
Your loop permits i to be size()-1 - So you're reading one past the end of the vector sentence.
while (i != sentence.size()) {
while (j != sentence.size()) {
...
++j;
}
++i;
}
j is never reset - next iteration of the outer loop it'll start at sentence... |
5,306,532 | 5,306,730 | Accessing attributes in C++ through getters-setters | Hi I have background in Java and currently learning C++. In Java it is not advisable to access the instance attributes directly, instance attributes are made private and accessed through getters-setters. Is it also advisable to create something like JavaBean in C++? Or is this not a common thing in the C++ lingo? If no... | This is really a general OO design question rather than a language question. Personally, I follow the school of thought "if you have many getters and mutators, your class design has a flaw". Public interface of a class is behavior, not its internal structure or some model of such structure. But of course it's just one ... |
5,306,555 | 5,307,072 | How to prevent floating point errors in camera vectors | On a different question, the user that answered (Ricky) me also said the following (which I still find a little confusing):
When I say they must remain
perpendicular, I only mean that if you
rotate vectors independently by the
same transformation over and over,
floating point errors may creep in and
they cou... | Hopefully the two current answers are adequate, so I'll just add on a theoretical note that the reason this arises and the reason it's not too important how you handle it is that the nine numbers that form a 3x3 rotation matrix and describe how your camera is oriented are more than necessary.
A rotation matrix is jus... |
5,306,696 | 5,306,747 | c++ Overload operator bool() gives an ambiguous overload error with operator+ | I'm compiling some c++ code of a class MegaInt which is a positive decimal type class that allows arithmetic operations on huge numbers.
I want to overload operator bool to allow code like this:
MegaInt m(45646578676547676);
if(m)
cout << "YaY!" << endl;
This is what I did:
header:
class MegaInt
{
public:
... | The C++ compiler is allowed to automatically convert bool into int for you, and that's what it wants to do here.
The way to solve this problem is to employ the safe bool idiom.
Technically, creating an operator void* is not an example of the safe bool idiom, but it's safe enough in practice, because the bool/int proble... |
5,306,745 | 5,306,773 | Getting only necessary headers out of boost | I need to submit an assignment, but I only want to include the header files from boost that I actually used (I made use of boost::shared_ptr and boost::function). I tried doing so manually, but I'm missing some header files and everytime i go to add them, it turns out I'm missing more. Is there a quick easy way to find... | The bcp command is made for this:
NAME
bcp - extract subsets of Boost
SYNOPSIS
bcp --list [options] module-list
bcp [options] module-list output-path
bcp --report [options] module-list html-file
bcp --help
DESCRIPTION
Copies all the files, including dependencies, found in module-list to
output-p... |
5,306,755 | 5,306,783 | Function template with return type T doesn't compile | The following code compiles fine:
template<typename T>
void f(const T &item) { return; }
int main()
{
f("const string literal");
}
Compilation succeeded at ideone : http://ideone.com/dR6iZ
But when I mention the return type, it doesn't compile:
template<typename T>
T f(const T &item) { return item; }
int main()
... | You cannot return an array from a function, so template instantiation fails, and there's no matching function.
You get this particular error because of SFINAE - It's not really an error that the compiler cannot instantiate your function, it is an error that there's no matching function.
You can return a reference to an... |
5,306,762 | 5,306,800 | Bit Operation in C / C++ | When we talk Bit Operation in C or C++.
Does bit start from bit0 or bit1 ? Which one is more make sense?
As I know A bit can assume either of two values: 1 or 0.
| Generally, bit identifiers start from 0 at the least significant end, such as with the following octet:
+----+----+----+----+----+----+----+----+
| b7 | b6 | b5 | b4 | b3 | b2 | b1 | b0 |
+----+----+----+----+----+----+----+----+
80 40 20 10 08 04 02 01 <-- hex value
While a bit can take either a 0 ... |
5,306,801 | 5,307,181 | Optional Error Handling | I have a create method as shown below, in which I want to (if the return is a null pointer) get the error from. However I want this error handling to be optional, and not a requirement in calling the function.
The code:
class foo {
foo() {...};
public:
~foo();
static foo* createFoo(int aparam = 42, int bpar... | I don't know that I can offer best practice but here is my perspective.
Checking for NULL (a failed allocation) is standard practice in C and C++, it is a well understood and easily recognized idiom. The addition of an optional error code, while providing flexibility also adds arguably unneeded complexity. It burdens t... |
5,306,822 | 5,306,980 | C++ HTTP always 301 using sockets | I'm sick of this. ALWAYS when I make a HTTP GET query from a C/C++ program using just plain sockets I get 301 Moved Permanently's. Normally I'd use libcURL, but in this case I don't want to add another library, I just need to download one flat identification file from one fixed server.
This is my current query:
GET /ga... | Alright, besides the issue with the Accept-Encoding, the query was fine. The problem was that I resolved in my socket code to "minecraft.net" instead of "www.minecraft.net". RAAAAH. Fixed.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.