question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,609,229 | 2,609,283 | Basic Custom String Class for C++ | EDIT: I don't want to delete the post because I have learned a lot very quickly from it and it might do someone else good, but there is no need for anyone else to spend time answering or viewing this question. The problems were in my programming fundamentals, and that is something that just can't be fixed in a quick response. To all who posted, thanks for the help, quite humbling!
Hey all, I'm working on building my own string class with very basic functionality. I am having difficulty understand what is going on with the basic class that I have define, and believe there is some sort of error dealing with the scope occurring. When I try to view the objects I created, all the fields are described as (obviously bad pointer). Also, if I make the data fields public or build an accessor method, the program crashes. For some reason the pointer for the object is 0xccccccccc which points to no where.
How can a I fix this? Any help/comments are much appreciated.
//This is a custom string class, so far the only functions are
//constructing and appending
#include<iostream>
using namespace std;
class MyString1
{
public:
MyString1()
{
//no arg constructor
char *string;
string = new char[0];
string[0] ='\0';
std::cout << string;
size = 1;
}
//constructor receives pointer to character array
MyString1(char* chars)
{
int index = 0;
//Determine the length of the array
while (chars[index] != NULL)
index++;
//Allocate dynamic memory on the heap
char *string;
string = new char[index+1];
//Copy the contents of the array pointed by chars into string, the char array of the object
for (int ii = 0; ii < index; ii++)
string[ii] = chars[ii];
string[index+1] = '\0';
size = index+1;
}
MyString1 append(MyString1 s)
{
//determine new size of the appended array and allocate memory
int newsize = s.size + size;
MyString1 MyString2;
char *newstring;
newstring = new char[newsize+1];
int index = 0;
//load the first string into the array
for (int ii = 0; ii < size; ii++)
{
newstring[ii] = string[ii];
index++;
}
for(int jj = 0; jj < s.size; jj++, ii++)
{
newstring[ii] = s.string[jj++];
index++;
}
//null terminate
newstring[newsize+1] = '\0';
delete string;
//generate the object for return
MyString2.string=newstring;
MyString2.size=newsize;
return MyString2;
}
private:
char *string;
int size;
};
int main()
{
MyString1 string1;
MyString1 string2("Hello There");
MyString1 string3("Buddy");
string2.append(string3);
return 0;
}
EDIT:
Thank you everyone so far who has responded and dealing with my massive lack of understanding of this topic. I'll begin to work with all of the answers, but thanks again for the good responses, sorry my question is vague, but there isn't really a specific error, but more of a lack of understanding of arrays and classes.
| Here's just the mistakes from the first constructor.
MyString1()
{
//no arg constructor
char *string; //defines local variable that hides the member by that name
string = new char[0]; //sort of meaningless
string[0] ='\0'; //not enough room for that (out-of-bounds)
std::cout << string;
size = 1; //I don't think you should count null as part of the string
}
Similar mistakes elsewhere.
Also you should pass parameters in a more careful way.
MyString1(const char* source); //note const
MyString1 append(const MyString1& what); //note const and reference
If the latter is correct, also depends on what it is supposed to do. Based on std::string the expected result would be:
MyString1 a("Hello "), b("world");
a.append(b);
assert(a == "Hello world");
|
2,609,299 | 2,609,404 | Use-cases of pure virtual functions with body? | I recently came to know that in C++ pure virtual functions can optionally have a body.
What are the real-world use cases for such functions?
| The classic is a pure virtual destructor:
class abstract {
public:
virtual ~abstract() = 0;
};
abstract::~abstract() {}
You make it pure because there's nothing else to make so, and you want the class to be abstract, but you have to provide an implementation nevertheless, because the derived classes' destructors call yours explicitly. Yeah, I know, a pretty silly textbook example, but as such it's a classic. It must have been in the first edition of The C++ Programming Language.
Anyway, I can't remember ever really needing the ability to implement a pure virtual function. To me it seems the only reason this feature is there is because it would have had to be explicitly disallowed and Stroustrup didn't see a reason for that.
If you ever feel you need this feature, you're probably on the wrong track with your design.
|
2,609,539 | 2,609,574 | Any difference in compiler behavior for each of these snippets? | Please consider following code:
1.
uint16 a = 0x0001;
if(a < 0x0002)
{
// do something
}
2.
uint16 a = 0x0001;
if(a < uint16(0x0002))
{
// do something
}
3.
uint16 a = 0x0001;
if(a < static_cast<uint16>(0x0002))
{
// do something
}
4.
uint16 a = 0x0001;
uint16 b = 0x0002;
if(a < b)
{
// do something
}
What compiler does in backgorund and what is the best (and correct) way to do above testing?
p.s. sorry, but I couldn't find the better title :)
EDIT:
values 0x0001 and 0x0002 are only example. There coudl be any 2 byte value instead.
Thank you in advance!
| The last example is the best code-wise, as you shouldn't use "magic constants" in your code.
In fact, the best way would be to make b const, (edit) and use meaningful names:
uint16 currentSpeed = 0x0001;
const uint16 cMaxSpeed = 0x0002;
if (currentSpeed < cMaxSpeed)
{
// do something
}
Other than that, there is very little difference "under the bonnet" between your examples.
|
2,609,642 | 2,609,667 | C++ argv path specifier | In the interpreter for my programming languages I have to correctly handle the parts in case the import function is called. I then need to check if such a file is in the /libs folder (located at the same place as my executeable!) and if it doesn't exist I have to check in the directory of the current script.
How can I get the exact path to the directory where the executeable is located from argv?
What is the best way to remove the file from the end of a path, e.g:
C:/a/b/c/file.exe should become C:/a/b/c/
|
There is no guaranteed way to do that. You can try looking in argv[0] but whether that has the full path or just the name of the binary depends on the platform and how your process was invoked.
You can use strrchr to find the last slash and replace the character after it with '\0'
Code example:
// Duplicate the string so as not to trash the original
// You can skip this if you don't mind modifying the original data
// and the originald is writeable (i.e. no literal strings)
char *path = strdup(...);
char *last_slash = strrchr(path, '/');
if (last_slash)
{
#if PRESERVE_LAST_SLASH
*(last_slash + 1) = '\0';
#else
*last_slash = '\0';
#endif
}
|
2,609,706 | 2,610,081 | Is there an equivalent to BCEL (Java .class manipulation) but in C or C++ | Is there a C or C++ compatible library for reading and writing Java class files?
I.e. something like Apache BCEL.
| None that I'm aware of. However, you can call Java from C++. That will let you use BCEL from C++. If you're on one of gcj's supported platforms, you could try using it to compile BCEL to native code.
|
2,609,723 | 2,609,800 | C++ and Dependency Injection in unit testing | Suppose I have a C++ class like so:
class A
{
public:
A()
{
}
void SetNewB( const B& _b ) { m_B = _b; }
private:
B m_B;
}
In order to unit test something like this, I would have to break A's dependency on B. Since class A holds onto an actual object and not a pointer, I would have to refactor this code to take a pointer. Additionally, I would need to create a parent interface class for B so I can pass in my own fake of B when I test SetNewB.
In this case, doesn't unit testing with dependency injection further complicate the existing code? If I make B a pointer, I'm now introducing heap allocation, and some piece of code is now responsible for cleaning it up (unless I use ref counted pointers). Additionally, if B is a rather trivial class with only a couple of member variables and functions, why introduce a whole new interface for it instead of just testing with an instance of B?
I suppose you could make the argument that it would be easier to refactor A by using an interface. But are there some cases where two classes might need to be tightly coupled?
| I think you're taking the idea of Unit Testing too far. In this case, A and B are one unit, i.e., A can't exist without B. First, test B and make sure it passes all of the B-specific unit tests, then once that passes, test A and make sure it behave how it's supposed to.
|
2,610,449 | 2,610,465 | Why does C++ allow variable length arrays that aren't dynamically allocated? | I'm relatively new to C++, and from the beginning it's been drilled into me that you can't do something like
int x;
cin >> x;
int array[x];
Instead, you must use dynamic memory. However, I recently discovered that the above will compile (though I get a -pedantic warning saying it's forbidden by ISO C++). I know that it's obviously a bad idea to do it if it's not allowed by the standard, but I previously didn't even know this was possible.
My question is, why does g++ allow variable length arrays that aren't dynamically allocated if it's not allowed by the standard? Also, if it's possible for the compiler to do it, why isn't it in the standard?
| Support for variable length arrays (VLAs) was added to the C language in C99.
It's likely that since support for them exists in gcc (to support C99), it was relatively straightforward to add support for them to g++.
That said, it's an implementation-specific language extension, and it's not a good idea to use implementation-specific extensions if you want your code to be portable.
|
2,610,744 | 2,610,772 | Problem Making C++ script | I am not sure if I can post this sort of question (apologies in advance) but I am trying to build something from this blog post.
# mkdir wkthumb
# cat > wkthumb.cpp
# qmake -project
# qmake && make
# ./wkthumb
I have no experience with this, but I download all the files needed in the directory wkthumb using git. I have gone inside this directory and tried to execute cat > wkthumb.cpp - this just hangs for me. In addition, I thought cat was supposed to be used like this: cat file1.txt file2.txt > file3.txt? The above is blank with the first arguments?
I am using Fedora Core 10.
| The command
cat > wkthumb.cpp
reads from stdin and writes to the file wkthumb.cpp. When you run that it's not hanging, but rather it's waiting for you to type some source code. Copy and paste the source code in that blog post, followed by CtrlD Enter to create the wkthumb.cpp file.
Or, if you've already downloaded wkthumb.cpp through some other method, simply skip the above step.
|
2,610,890 | 2,610,919 | Convert templated parameter type to string | I've got a small bit of DRY going on in code I and others have written that I'd like to reduce but I'm failing to figure out how to get it done. This is legacy COM code but it's interfering with the readability. I'd like to do the following:
bool queryInterface<class T, class V>(T &_input, V &_output, Logger &_logger){
if( FAILED( _input->QueryInterface( &_output ) ) ){
_logger.error() << "Failed to Query Interface between " << MAGICHAPPENS<T>()
<< " and " << MAGICHAPPENS<V>();
return false;
}
if( _output == NULL ){
_logger.warn() << "Unable to Query Interface between " << MAGICHAPPENS<T>()
<< " and " << MAGICHAPPENS<V>();
return false;
}
}
Wherein the "MAGICHAPPENS()" function would spit out the name of the variable type. Such that if "V" were a IQueryFilter I'd get back a string of "IQueryFilter." I can't think of any reasonable solution without having to write a bunch of template specializations totally defeating the point in the first place.
Is there a way to write ANDMAGICHAPPENS?
| You can use RTTI to get the variable name:
#include <typeinfo>
template <typename T>
const char* type_name(void)
{
// this, unfortunately, is implementation defined
// and is allowed to be an empty string (useless!)
return typeid(T).name();
}
_logger.error() << "Failed to Query Interface between " << type_name<T>()
<< " and " << type_name<V>();
Like the comments say, name() isn't guaranteed to be any particular formatting of the name, or any name at all. But it does require RTTI, which some people dislike.
|
2,610,934 | 2,611,094 | Make Errors: Missing Includes in C++ Script? | I just got help in how to compile this script a few mintues ago on SO but I have managed to get errors. I am only a beginner in C++ and have no idea what the below erros means or how to fix it.
This is the script in question. I have read the comments from some users suggesting they changed the #include parts but it seems to be exactly what the script has, see this comment.
[root@localhost wkthumb]# qmake-qt4 && make
g++ -c -pipe -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -I/usr/lib/qt4/mkspecs/linux-g++ -I. -I/usr/include/QtCore -I/usr/include/QtGui -I/usr/include -I. -I. -I. -o main.o main.cpp
main.cpp:5:20: error: QWebView: No such file or directory
main.cpp:6:21: error: QWebFrame: No such file or directory
main.cpp:8: error: expected constructor, destructor, or type conversion before ‘*’ token
main.cpp:11: error: ‘QWebView’ has not been declared
main.cpp: In function ‘void loadFinished(bool)’:
main.cpp:18: error: ‘view’ was not declared in this scope
main.cpp:18: error: ‘QWebSettings’ has not been declared
main.cpp:19: error: ‘QWebSettings’ has not been declared
main.cpp:20: error: ‘QWebSettings’ has not been declared
main.cpp: In function ‘int main(int, char**)’:
main.cpp:42: error: ‘view’ was not declared in this scope
main.cpp:42: error: expected type-specifier before ‘QWebView’
main.cpp:42: error: expected `;' before ‘QWebView’
make: *** [main.o] Error 1
I have the web kit on my Fedora Core 10 machine:
qt-4.5.3-9.fc10.i386
qt-devel-4.5.3-9.fc10.i386
Thanks all for any help
| The error message indicates that the compiler cannot find what you're trying to include, i.e. <QWebView>. The way to tell the compiler where to look is with the -I flag, to specify include directories (these are not recursive).
Currently, you set the following include dirs:
-I/usr/lib/qt4/mkspecs/linux-g++
-I.
-I/usr/include/QtCore
-I/usr/include/QtGui
-I/usr/include
You need to find where QWebView is located on your system, and add the include path to the commandline (or install QWebView into one of the above dirs).
General note: When you get a lot of errors like this, focus on the first one or two. The later errors (such as ‘QWebView’ has not been declared) will probably be solved by fixing the missing-include error.
|
2,611,081 | 2,611,223 | Combine two numbers into one. Example: 123 and 456 become 123456 | In C++, how do I combine (note: not add) two integers into one big integer?
For example:
int1 = 123;
int2 = 456;
Is there a function to take the two numbers and turn intCombined into 123456?
EDIT:
My bad for not explaining clearly. If int2 is 0, then the answer should be 123, not 1230. In actuality though, int1 (the number on the left side) would only have a value if int2 goes over the 32 bit limit. So when int2 is 0, then int1 is 0 (or garbage, i'm not sure).
| The power of ten, that you need to multiply the first number with, is the smallest one, that is bigger than the second number:
int combine(int a, int b) {
int times = 1;
while (times <= b)
times *= 10;
return a*times + b;
}
|
2,611,246 | 2,611,256 | Is "for(;;)" faster than "while (true)"? If not, why do people use it? | for (;;) {
//Something to be done repeatedly
}
I have seen this sort of thing used a lot, but I think it is rather strange...
Wouldn't it be much clearer to say while(true), or something along those lines?
I'm guessing that (as is the reason for many-a-programmer to resort to cryptic code) this is a tiny margin faster?
Why, and is it really worth it? If so, why not just define it this way:
#define while(true) for(;;)
See also: Which is faster: while(1) or while(2)?
|
It's not faster.
If you really care, compile with assembler output for your platform and look to see.
It doesn't matter. This never matters. Write your infinite loops however you like.
|
2,611,357 | 2,611,616 | lambda traits inconsistency across C++0x compilers | I observed some inconsistency between two compilers (g++ 4.5, VS2010 RC) in the way they match lambdas with partial specializations of class templates. I was trying to implement something like boost::function_types for lambdas to extract type traits. Check this for more details.
In g++ 4.5, the type of the operator() of a lambda appears to be like that of a free standing function (R (*)(...)) whereas in VS2010 RC, it appears to be like that of a member function (R (C::*)(...)). So the question is are compiler writers free to interpret any way they want? If not, which compiler is correct? See the details below.
template <typename T>
struct function_traits
: function_traits<decltype(&T::operator())>
{
// This generic template is instantiated on both the compilers as expected.
};
template <typename R, typename C>
struct function_traits<R (C::*)() const> { // inherits from this one on VS2010 RC
typedef R result_type;
};
template <typename R>
struct function_traits<R (*)()> { // inherits from this one on g++ 4.5
typedef R result_type;
};
int main(void) {
auto lambda = []{};
function_traits<decltype(lambda)>::result_type *r; // void *
}
This program compiles on both g++ 4.5 and VS2010 but the function_traits that are instantiated are different as noted in the code.
| I believe that GCC is noncompliant. N3092 §5.1.2/5 says
The closure type for a
lambda-expression has a public inline
function call operator (13.5.4) whose
param- eters and return type are
described by the lambda-expression’s
parameter-declaration-clause and
trailing- return-type respectively.
This function call operator is
declared const (9.3.1) if and only if
the lambda- expression’s
parameter-declaration-clause is not
followed by mutable.
So while many things about the closure object's type are implementation-defined, the function itself must be a member to be public and must be a nonstatic member to be const.
EDIT: This program indicates that operator() is a member function on GCC 4.6, which is essentially the same as 4.5.
#include <iostream>
#include <typeinfo>
using namespace std;
template< class ... > struct print_types {};
template<> struct print_types<> {
friend ostream &operator<< ( ostream &lhs, print_types const &rhs ) {
return lhs;
}
};
template< class H, class ... T > struct print_types<H, T...> {
friend ostream &operator<< ( ostream &lhs, print_types const &rhs ) {
lhs << typeid(H).name() << " " << print_types<T...>();
return lhs;
}
};
template< class T >
struct spectfun {
friend ostream &operator<< ( ostream &lhs, spectfun const &rhs ) {
lhs << "unknown";
return lhs;
}
};
template< class R, class ... A >
struct spectfun< R (*)( A ... ) > {
friend ostream &operator<< ( ostream &lhs, spectfun const &rhs ) {
lhs << "returns " << print_types<R>()
<< " takes " << print_types<A ...>();
return lhs;
}
};
template< class C, class R, class ... A >
struct spectfun< R (C::*)( A ... ) > {
friend ostream &operator<< ( ostream &lhs, spectfun const &rhs ) {
lhs << "member of " << print_types<C>() << ", " << spectfun<R (*)(A...)>();
return lhs;
}
};
template< class T >
struct getcall {
typedef decltype(&T::operator()) type;
};
int main() {
int counter = 0;
auto count = [=]( int ) mutable { return ++ counter; };
cerr << spectfun< getcall<decltype(count)>::type >() << endl;
}
output:
member of Z4mainEUlvE_, returns i takes i
EDIT: It looks like the only problem is that pointers to certain closure call operators fail to match ptmf template patterns. The workaround is to declare the lambda expression mutable. This is meaningless if there is no capture and only (aside from fixing the problem) seems to change the const-ness of the call operator.
template< class T >
struct getcall {
typedef decltype(&T::operator()) type;
static type const value;
};
template< class T >
typename getcall<T>::type const getcall<T>::value = &T::operator();
int main() {
auto id = []( int x ) mutable { return x; };
int (*idp)( int ) = id;
typedef decltype(id) idt;
int (idt::*idptmf)( int ) /* const */ = getcall< decltype(id) >::value;
cerr << spectfun< decltype(idp) >() << endl;
cerr << spectfun< decltype(idptmf) >() << endl;
cerr << spectfun< getcall<decltype(id)>::type >() << endl;
output:
returns i takes i
member of Z4mainEUliE0_ , returns i takes i
member of Z4mainEUliE0_ , returns i takes i
Without the mutable and with the const, spectfun does not print signatures for either of the last two queries.
|
2,611,359 | 2,611,425 | Learning to read GCC assembler output | I'm considering picking up some very rudimentary understanding of assembly. My current goal is simple: VERY BASIC understanding of GCC assembler output when compiling C/C++ with the -S switch for x86/x86-64.
Just enough to do simple things such as looking at a single function and verifying whether GCC optimizes away things I expect to disappear.
Does anyone have/know of a truly concise introduction to assembly, relevant to GCC and specifically for the purpose of reading, and a list of the most important instructions anyone casually reading assembly should know?
| If you're using gcc or clang, the -masm=intel argument tells the compiler to generate assembly with Intel syntax rather than AT&T syntax, and the --save-temps argument tells the compiler to save temporary files (preprocessed source, assembly output, unlinked object file) in the directory GCC is called from.
Getting a superficial understanding of x86 assembly should be easy with all the resources out there. Here's one such resource: http://www.cs.virginia.edu/~evans/cs216/guides/x86.html .
You can also just use disasm and gdb to see what a compiled program is doing.
|
2,611,556 | 2,611,605 | Containers of reference_wrappers (comparison operators required?) | If you use stl containers together with reference_wrappers of POD types, code such as the following works just fine:
int i = 0;
std::vector< boost::reference_wrapper<int> > is;
is.push_back(boost::ref(i));
std::cout << (std::find(is.begin(),is.end(),i)!=is.end()) << std::endl;
However, if you use non-POD types like (contrived example):
struct Integer
{
int value;
bool operator==(const Integer& rhs) const
{
return value==rhs.value;
}
bool operator!=(const Integer& rhs) const
{
return !(*this == rhs);
}
};
It doesn't suffice to declare the comparison operators above, aditionally you have to declare:
bool operator==(const boost::reference_wrapper<Integer>& lhs, const Integer& rhs)
{
return boost::unwrap_ref(lhs)==rhs;
}
And possibly also:
bool operator==(const Integer& lhs, const boost::reference_wrapper<Integer>& rhs)
{
return lhs==boost::unwrap_ref(rhs);
}
In order to get the equivalent code to work:
Integer j = { 0 };
std::vector< boost::reference_wrapper<Integer> > js;
js.push_back(boost::ref(j));
std::cout << (std::find(js.begin(),js.end(),j)!=js.end()) << std::endl;
Now, I'm wondering if this is really the way it's meant to be done, since it's somewhat impractical. It just seems there should be a simpler solution, e.g. templates:
template<class T>
bool operator==(const boost::reference_wrapper<T>& lhs, const T& rhs)
{
return boost::unwrap_ref(lhs)==rhs;
}
template<class T>
bool operator==(const T& lhs, const boost::reference_wrapper<T>& rhs)
{
return lhs==boost::unwrap_ref(rhs);
}
There's probably a good reason why reference_wrapper behaves the way it does (possibly to accomodate non-POD types without comparison operators?). Maybe there already is an elegant solution and I just haven't found it.
| Does the example above work when you declare the original comparison routines as such:
friend bool operator==(const Integer& lhs, const Integer& rhs)
{
return lhs.value == rhs.value;
}
friend bool operator!=(const Integer& lhs, const Integer& rhs)
{
return !(lhs == rhs);
}
Note that declaring a friend comparison routine in the class is not the same as declaring a member function comparison routine, which is why these may work while your original code may not.
|
2,611,690 | 2,611,814 | Returning C++ objects from Windows DLL | Due to how Microsoft implements the heap in their non-DLL versions of the runtime, returning a C++ object from a DLL can cause problems:
// dll.h
DLL_EXPORT std::string somefunc();
and:
// app.c - not part of DLL but in the main executable
void doit()
{
std::string str(somefunc());
}
The above code runs fine provided both the DLL and the EXE are built with the Multi-threaded DLL runtime library.
But if the DLL and EXE are built without the DLL runtime library (either the single or multi-threaded versions), the code above fails (with a debug runtime, the code aborts immediately due to the assertion _CrtIsValidHeapPointer(pUserData) failing; with a non-debug runtime the heap gets corrupted and the program eventually fails elsewhere).
Two questions:
Is there a way to solve this other then requiring that all code use the DLL runtime?
For people who distribute their libraries to third parties, how do you handle this? Do you not use C++ objects in your API? Do you require users of your library to use the DLL runtime? Something else?
| There is a way to deal with this, but it's somewhat non-trivial. Like most of the rest of the library, std::string doesn't allocate memory directly with new -- instead, it uses an allocator (std::allocator<char>, by default).
You can provide your own allocator that uses your own heap allocation routines that are common to the DLL and the executable, such as by using HeapAlloc to obtain memory, and suballocate blocks from there.
|
2,611,764 | 2,611,883 | Can I use a binary literal in C or C++? | I need to work with a binary number.
I tried writing:
const char x = 00010000;
But it didn't work.
I know that I can use a hexadecimal number that has the same value as 00010000, but I want to know if there is a type in C++ for binary numbers, and if there isn't, is there another solution for my problem?
| You can use BOOST_BINARY while waiting for C++0x. :) BOOST_BINARY arguably has an advantage over template implementation insofar as it can be used in C programs as well (it is 100% preprocessor-driven.)
To do the converse (i.e. print out a number in binary form), you can use the non-portable itoa function, or implement your own.
Unfortunately you cannot do base 2 formatting with STL streams (since setbase will only honour bases 8, 10 and 16), but you can use either a std::string version of itoa, or (the more concise, yet marginally less efficient) std::bitset.
#include <boost/utility/binary.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <bitset>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
unsigned short b = BOOST_BINARY( 10010 );
char buf[sizeof(b)*8+1];
printf("hex: %04x, dec: %u, oct: %06o, bin: %16s\n", b, b, b, itoa(b, buf, 2));
cout << setfill('0') <<
"hex: " << hex << setw(4) << b << ", " <<
"dec: " << dec << b << ", " <<
"oct: " << oct << setw(6) << b << ", " <<
"bin: " << bitset< 16 >(b) << endl;
return 0;
}
produces:
hex: 0012, dec: 18, oct: 000022, bin: 10010
hex: 0012, dec: 18, oct: 000022, bin: 0000000000010010
Also read Herb Sutter's The String Formatters of Manor Farm for an interesting discussion.
|
2,611,803 | 2,611,809 | Compiler issues on VC++ 2008 Express, Seemingly correct code throws errors | I've been trying to get back into coding for a while, so I figured I'd start with some simple SDL, now, without the file i/o, this compiles fine, but when I throw in the stdio code, it starts throwing errors. This I'm not sure about, I don't see any problem with the code itself, however, like I said, I might as well be a newbie, and figured I'd come here to get someone with a little more experience with this type of thing to look at it.
I guess my question boils down to: "Why doesn't this compile under Microsoft's Visual C++ 2008 Express?"
I've attached the error log at the bottom of the code snippet. Thanks in advance for any help.
#include "SDL/SDL.h"
#include "stdio.h"
int main(int argc, char *argv[])
{
FILE *stderr;
FILE *stdout;
stderr = fopen("stderr", "wb");
stdout = fopen("stdout", "wb");
SDL_Init(SDL_INIT_EVERYTHING);
fprintf(stdout, "SDL INITIALIZED SUCCESSFULLY\n");
SDL_Quit();
fprintf(stderr, "SDL QUIT.\n");
fclose(stderr);
fclose(stdout);
return 0;
}
Actual errors reported:
main.cpp(6) : error C2090: function returns array
main.cpp(6) : error C2528: '__iob_func' : pointer to reference is illegal
main.cpp(6) : error C2556: 'FILE ***__iob_func(void)' : overloaded function differs only by return type from 'FILE *__iob_func(void)'
c:\program files\microsoft visual studio 9.0\vc\include\stdio.h(132) : see declaration of '__iob_func'
main.cpp(7) : error C2090: function returns array
main.cpp(7) : error C2528: '__iob_func' : pointer to reference is illegal
main.cpp(9) : error C2440: '=' : cannot convert from 'FILE *' to 'FILE ***'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
main.cpp(10) : error C2440: '=' : cannot convert from 'FILE *' to 'FILE ***'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
main.cpp(13) : error C2664: 'fprintf' : cannot convert parameter 1 from 'FILE ***' to 'FILE *'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
main.cpp(15) : error C2664: 'fprintf' : cannot convert parameter 1 from 'FILE ***' to 'FILE *'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
main.cpp(17) : error C2664: 'fclose' : cannot convert parameter 1 from 'FILE ***' to 'FILE *'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
main.cpp(18) : error C2664: 'fclose' : cannot convert parameter 1 from 'FILE ***' to 'FILE *'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
| #include "SDL/SDL.h"
#include "stdio.h"
int main(int argc, char *argv[])
{
FILE *stderr; //Invalid names. These are already defined by stdio.h.
FILE *stdout; //You can't use them (portably anyway).
stderr = fopen("stderr", "wb"); //I'm assuming you actually want files
stdout = fopen("stdout", "wb"); //called "stderror" and "stdout".
SDL_Init(SDL_INIT_EVERYTHING);
fprintf(stdout, "SDL INITIALIZED SUCCESSFULLY\n");
SDL_Quit();
fprintf(stderr, "SDL QUIT.\n");
fclose(stderr);
fclose(stdout);
return 0;
}
Try changing the names stderr and stdout to something else. I suspect the compiler is complaining because these are already defined elsewhere in the C library.
|
2,611,871 | 2,611,884 | class header+ implementation | what am I doing wrong here? I keep on getting a compilation error when I try to run this in codelab (turings craft)
Instructions:
Write the implementation (.cpp file) of the GasTank class of the previous exercise. The full specification of the class is:
A data member named amount of type double.
A constructor that no parameters. The constructor initializes the data member amount to 0.
A function named addGas that accepts a parameter of type double . The value of the amount instance variable is increased by the value of the parameter.
A function named useGas that accepts a parameter of type double . The value of the amount data member is decreased by the value of the parameter.
A function named getGasLevel that accepts no parameters. getGasLevel returns the value of the amount data member.
class GasTank{
double amount;
GasTank();
void addGas(double);
void useGas(double);
double getGasLevel();};
GasTank::GasTank(){
amount=0;}
double GasTank::addGas(double a){
amount+=a;}
double GasTank::useGas(double a){
amount+=a;}
double GasTank::getGasLevel(){
return amount;}
| You listed both the class declaration and its function implementations. What part of code is in the header file, and what part of it is in the implementation file?
Also, recall that for a class the default visibility is private. Therefore, all your functions are private -- including the constructor! -- so you can't instantiate an object of the class. Try changing the visibility of the relevant functions to public.
Make sure the function signatures in the class declaration and the class definition match. So, if you declare
class GasTank {
// ...
public:
void addGas(double);
// ...
};
make sure you define
void GasTank::addGas(double d)
{
// ...
}
and not
double GasTank::addGas(double d)
{
// ...
}
One last thing: do indent your code properly. There's then a higher chance you marker (and us) will be in a good mood while reading your code.
|
2,611,977 | 2,612,308 | Refactor Pro versus Visual Assist X for C++ Development | There are two major refactoring tools which can be installed for Visual Studio that provide C++ support. The full versions of both tools are $250, and they seem to offer similar functionality. They are:
Developer Express' Refactor Pro + CodeRush
Whole Tomato's Visual Assist X
Which tool is better?
EDIT: My initial evaluation of the tools seems to be that Refactor Pro/CodeRush has several more features, but is also quite buggy on occasion. It doesn't seem to like macros:
(source: billy-oneal.com)
Here's Visual Assist's interpretation of the same:
(source: billy-oneal.com)
EDIT2: I think I like CodeRush over Visual Assist, but I'm not sure I can trust CR. CodeRush does seem to have problems parsing some C++ constructs, like the macros above. But it's UI is much more polished. For example:
(source: billy-oneal.com)
On the other hand Visual Assist X seems to have a much larger following among C++ developers, and it's code analysis is MUCH better. It doesn't seem to make mistakes like R! Pro was making from time to time.
I think at this point I just have to play with both tools and see which one proves more useful. But I'm still curious if anyone has had horror / success stories with either tool.
| I have used Visual Assist for years and I think it makes VS heaps more convenient for C++ development. The searchable file list, Go to Declaration and Rename functions in particular have been indispensable. VS2010 probably makes some of Visual Assist features obsolete but I imagine it will continue to be useful.
There are some situations where Visual Assist will stumble and not parse the code correctly, but they are few and far between, and it improves with every version.
I haven't used Refactor Pro so I can't say anything about it unfortunately.
|
2,612,063 | 2,612,067 | Operator Overloading in C | In C++, I can change the operator on a specific class by doing something like this:
MyClass::operator==/*Or some other operator such as =, >, etc.*/(Const MyClass rhs) {
/* Do Stuff*/;
}
But with there being no classes (built in by default) in C. So, how could I do operator overloading for just general functions?
For example, if I remember correctly, importing stdlib.h gives you the -> operator, which is just syntactic sugar for (*strcut_name).struct_element.
So how can I do this in C?
Thank you.
| Plain old C does not have operator overloading in any form. The -> "operator" to access a member of a pointer is standard C and is not introduced by any header file.
|
2,612,116 | 2,612,136 | operator<< cannot output std::endl -- Fix? | The following code gives an error when it's supposed to output just std::endl:
#include <iostream>
#include <sstream>
struct MyStream {
std::ostream* out_;
MyStream(std::ostream* out) : out_(out) {}
std::ostream& operator<<(const std::string& s) {
(*out_) << s;
return *out_;
}
};
template<class OutputStream>
struct Foo {
OutputStream* out_;
Foo(OutputStream* out) : out_(out) {}
void test() {
(*out_) << "OK" << std::endl;
(*out_) << std::endl; // ERROR
}
};
int main(int argc, char** argv){
MyStream out(&std::cout);
Foo<MyStream> foo(&out);
foo.test();
return EXIT_SUCCESS;
}
The error is:
stream1.cpp:19: error: no match for 'operator<<' in '*((Foo<MyStream>*)this)->Foo<MyStream>::out_ << std::endl'
stream1.cpp:7: note: candidates are: std::ostream& MyStream::operator<<(const std::string&)
So it can output a string (see line above the error), but not just the std::endl, presumably because std::endl is not a string, but the operator<< definition asks for a string.
Templating the operator<< didn't help:
template<class T>
std::ostream& operator<<(const T& s) { ... }
How can I make the code work? Thanks!
| You need to add this to your struct MyStream:
std::ostream& operator<<( std::ostream& (*f)(std::ostream&) )
{
return f(*out_);
}
std::endl is a function that appends a newline and flushes the underlying stream; this function signature accepts that function and applies it to the ostream member.
Then, as a test, defining foo::test as
void test() {
(*out_) << "start";
(*out_) << std::endl;
(*out_) << "done";
}
will correctly output
start
done
|
2,612,323 | 2,612,455 | C++ design: container of instances and pointers | I'm wondering something.
I have class Polygon, which composes a vector of Line (another class here)
class Polygon
{
std::vector<Line> lines;
public:
const_iterator begin() const;
const_iterator end() const;
}
On the other hand, I have a function, that calculates a vector of pointers to lines, and based on those lines, should return a pointer to a Polygon.
Polygon* foo(Polygon& p){
std::vector<Line> lines = bar (p.begin(),p.end());
return new Polygon(lines);
}
Here's the question:
I can always add a Polygon (vector
Is there a better way than dereferencing each element of the vector and assigning it to the existing vector container?
//for line in vector<Line*> v
//vcopy is an instance of vector<Line>
vcopy.push_back(*(v.at(i))
I think not, but I don't really like that approach.
Hopefully, I will be able to convince the author of the class to change it, but I can't base my coding right now to that fact (and I'm scared of a performance hit).
Thanks in advance.
| You can transform() the container:
struct deref { // NO! I don't want to derive, LEAVE ME ALONE!
template<typename P>
const P& operator()(const P* const p) const { return *p; }
};
// ...
vector<Line*> orig; // assume full ...
vector<Line> cp(orig.size());
transform(orig.begin(), orig.end(), cp.begin(), deref());
|
2,612,343 | 2,612,508 | basic boost date_time input format question | I've got a pointer to a string, (char *) as input. The date/time looks like this:
Sat, 10 Apr 2010 19:30:00
I'm only interested in the date, not the time.
I created an "input_facet" with the format I want:
boost::date_time::date_input_facet inFmt("%a %d %b %Y");
but I'm not sure what to do with it. Ultimately I'd like to create a date object from the string. I'm pretty sure I'm on the right track with that input facet and format, but I have no idea how to use it.
Thanks.
| You can't always dismiss the time part of a string due to time zone differences a date can change.
to parse date/time you could use time_input_facet<>
to extract a date part from it you could use .date() method
Example:
// $ g++ *.cc -lboost_date_time && ./a.out
#include <iostream>
#include <locale>
#include <sstream>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main() {
using namespace std;
using boost::local_time::local_time_input_facet;
using boost::posix_time::ptime;
stringstream ss;
ss << "Sat, 10 Apr 2010 19:30:00";
ss.imbue(locale(locale::classic(),
new local_time_input_facet("%a, %d %b %Y " "%H:%M:%S")));
ptime t;
ss.exceptions(ios::failbit);
ss >> t;
cout << "date: " << t.date() << '\n' ;
}
Run it:
$ g++ *.cc -lboost_date_time && ./a.out
date: 2010-Apr-10
|
2,612,447 | 2,612,524 | pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message | So I've been getting some mysterious uninitialized values message from valgrind and it's been quite the mystery as of where the bad value originated from.
Seems that valgrind shows the place where the unitialised value ends up being used, but not the origin of the uninitialised value.
==11366== Conditional jump or move depends on uninitialised value(s)
==11366== at 0x43CAE4F: __printf_fp (in /lib/tls/i686/cmov/libc-2.7.so)
==11366== by 0x43C6563: vfprintf (in /lib/tls/i686/cmov/libc-2.7.so)
==11366== by 0x43EAC03: vsnprintf (in /lib/tls/i686/cmov/libc-2.7.so)
==11366== by 0x42D475B: (within /usr/lib/libstdc++.so.6.0.9)
==11366== by 0x42E2C9B: std::ostreambuf_iterator<char, std::char_traits<char> > std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::_M_insert_float<double>(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, char, double) const (in /usr/lib/libstdc++.so.6.0.9)
==11366== by 0x42E31B4: std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::do_put(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, double) const (in /usr/lib/libstdc++.so.6.0.9)
==11366== by 0x42EE56F: std::ostream& std::ostream::_M_insert<double>(double) (in /usr/lib/libstdc++.so.6.0.9)
==11366== by 0x81109ED: Snake::SnakeBody::syncBodyPos() (ostream:221)
==11366== by 0x810B9F1: Snake::Snake::update() (snake.cpp:257)
==11366== by 0x81113C1: SnakeApp::updateState() (snakeapp.cpp:224)
==11366== by 0x8120351: RoenGL::updateState() (roengl.cpp:1180)
==11366== by 0x81E87D9: Roensachs::update() (rs.cpp:321)
As can be seen, it gets quite cryptic.. especially because when it's saying by Class::MethodX, it sometimes points straight to ostream etc. Perhaps this is due to optimization?
==11366== by 0x81109ED: Snake::SnakeBody::syncBodyPos() (ostream:221)
Just like that. Is there something I'm missing? What is the best way to catch bad values without having to resort to super-long printf detective work?
Update:
I found out what was wrong, but the strange thing is, valgrind did not report it when the bad value was first used. It was used in a multiplication function:
movespeed = stat.speedfactor * speedfac * currentbendfactor.val;
Where speedfac was an unitialised float. However, at that time it was not reported and not until the value is to be printed that I get the error.. Is there a setting for valgrind to change this behavior?
| Use the valgrind option --track-origins=yes to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.
Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:
It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.
From the Valgrind FAQ:
As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.
|
2,612,547 | 2,612,620 | Which file is the COM++ object and how do I import it to .NET? | I'm trying to write a COM++ object wrapper around a Qt widget (control) I wrote so I can use it in future .NET projects. e.g.:
public __gc class comWidget;
In the compile directory are the .exe, an exe.intermediate.manifest, and the comWidget.obj, and also some other crap files (.pdb, etc). So what/how do I import into .NET? I feel like I'm missing an important step for registering the object or whatever, but all these tutorials are terrible outdated and ridiculously unhelpful (for instance, I'm using the old CLR syntax because I can't find any good docs on the new stuff)
| Your question is worded so strangely, this can only be a guess, but I going to assume you want to write a user interface component for use in .NET projects. The host program will therefore usually be written in C# or VB.NET, and will be using either the Windows Forms or WPF as its user interface framework. You have some existing C++ code written using C++ with Qt that will do all the implementation for you, so you need to write a Windows Forms or WPF compatible UI widget in C++/CLI where the implementation is a Qt widget, right?
In Visual Studio 2008, start a new project. Pick C++ as the language and choose C++/CLL class library. Put in a dummy class:
public ref class Foo
{
public:
void Bar() { }
};
Build the project. In .NET the mother-of-all-output is your assembly, which for a library will be a .DLL. Now start a C# project (console application), and add a reference to the DLL you produced above. You can just browse for it on the hard drive.
In the C# project put something like this in the Main function:
var o = new MyClassLib.Foo();
o.Bar();
That's all there is to it. By building the assembly DLL in C++/CLI and then adding a reference to it in the C# project, its public ref class definitions are instantly available. No need to register anything.
Once you have this figured out, you need to decide what you're going to do about integrating a Qt widget (which I'm guessing boils down to a Win32 window handle?) into a .NET UI framework. It will be the most seamless in Windows Forms in which everything is Win32 windows, but you can also get it to work with the newer WPF too as it has a way of bridging in old controls.
This might be what you need to get started: http://msdn.microsoft.com/en-us/library/ms235628.aspx
|
2,612,598 | 2,612,612 | Returning a reference in C++ | Consider the following code where I am returning double& and a string&. It works fine in the case of a double but not in the case of a string. Why does the behavior differ?
In both cases the compiler does not even throw the Warning: returning address of local variable or temporary as I am returning a reference.
#include <iostream>
#include <string>
using namespace std;
double &getDouble(){
double h = 46.5;
double &refD = h;
return refD;
}
string &getString(){
string str = "Devil Jin";
string &refStr = str;
return refStr;
}
int main(){
double d = getDouble();
cout << "Double = " << d << endl;
string str = getString();
cout << "String = " << str.c_str() << endl;
return 0;
}
Output:
$ ./a.exe
Double = 46.5
String =
| You should never return a reference to a local variable no matter what the compiler does or does not do. The compiler may be fooled easily. you should not base the correctness of your code on some warning which may not have fired.
The reason it didn't fire here is probably that you're not literally returning a reference to a local variable, you are returning a variable that is a reference to a local variable. The compiler probably doesn't detect this somewhat more complex situation. It only detects things like:
string &getString(){
string str = "Devil Jin";
return str;
}
The case of the double is simpler because it doesn't involve constructing and destructing a complex object so in this situation the flow control analysis of the compiler probably did a better job at detecting the mistake.
|
2,612,652 | 2,612,760 | Refcounted pointers on iPhone | 1) Refcounted pointers need stack variables to have constructors / destructors called at predictable places.
2) Objective-C, afaik, does not support the above.
3) The cocoa libraries are bound in Objective-C, not C++.
Thus, my question: is there a easy way to use the Cocoa libraries, yet still have most of my app in C++ (and thus use my refcounted pointers)?
Thanks!
(iPhone in the title since this is mainly targeted at the iPhone)
| Yes, you can use Cocoa with C++. The gcc compiler will compile code that contains both C++ and Objective C constructs; the resulting language is called (somewhat predictably) Objective C++.
|
2,612,709 | 2,612,727 | Why does this Object wonk out & get deleted? | Stepping through the debugger, the BBox object is okay at the entry of the function, but as soon as it enters the function, the vfptr object points to 0xccccc. I don't get it.
What is causing this ?
Why is there a virtual table reference in there when the object is not derived from other class. (Though, it resides in GameObject from which my Player class inherits and I retrieve the BBox from within player. But, why does the BBox have the reference ? Shouldn't it be player who should be maintained in that reference ?)
For 1; some code for reference:
A. I retrieve the bounding box from player. This returns a bounding box as expected. I then send its address to GetGridCells.
const BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
boost::unordered_set < Cell*, CellPHash >& l_GridCells = GetGridCells ( &l_Bbox );
B. This is where a_pBoundingBox goes crazy and gets that garbage value.
boost::unordered_set< Cell*, CellPHash > CollisionMgr::GetGridCells(const BoundingBox *a_pBoundingBox)
{
I think the following code is also pertinent, so I'm sticking this in here anyways:
const BoundingBox& Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
const BoundingSphere& Player::GetBoundingSphere(void)
{
BoundingSphere& l_BSphere = m_pGeomMesh->m_BoundingSphere;
l_BSphere.m_Center = GetPosition();
return l_BSphere;
}
// BoundingBox Constructor
BoundingBox(const BoundingSphere* a_pBoundingSphere);
Can anyone please give me some idea as to why this is happening? Also, if you want me to post more code, please do let me know.
Thanks!
| const BoundingBox& Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
Here, you're returning a reference to a temporary BoundingBox object. That object goes out of scope as soon as the return statement ends.
Return a BoundingBox instead of a BoundingBox& instead.
Also:
BoundingSphere& l_BSphere = m_pGeomMesh->m_BoundingSphere;
l_BSphere.m_Center = GetPosition();
Here, you take a reference to the bounding sphere of the m_pGeomMesh, then modify the value it refers to. This will result in a modification of the original object. Are you sure this is what you want?
Also:
// BoundingBox Constructor
BoundingBox(const BoundingSphere* a_pBoundingSphere);
In the only place where using a reference makes a great deal of sense, you use a pointer instead. Why?
|
2,612,766 | 2,612,785 | Making use of C++ to speed up PHP | I saw this post on Sitepoint quoting a statement by Rasmus Lerdorf which goes (according to Sitepoint) as follows:
How can you make PHP fast? Well, you can’t" was his quick answer. PHP is simply not fast enough to scale to Yahoo levels. PHP was never meant for those sorts of tasks. "Any script based language is simply not fast enough". To get the speed that is necessary for truly massive web systems you have to use compiled C++ extensions to get true, scaleable architecture. That is what Yahoo does and so do many other PHP heavyweights.
Intrigued by the statement (not to mention the fact that up to now, all I was doing in PHP was small database-based applications), I was wondering how I could "use compiled C++ extensions" with PHP.
Any ideas or resources?
| Don't even bother. PHP is slow... You may create a mixture of C++ and PHP but you'll need to do lots of profiling to understand what is slow. And this is mostly... PHP.
See following:
C++ vs PHP Benchmarks for real web software
Is Data Base the Bottle Neck of Web Service? (not really... or why wikimedia has so many servers)
Slashdot article about Facebook (or how many resources PHP wastes)
Just write in C++ in first place. It is as simple as writing in PHP with modern C++ web framework and good knowledge in C++.
Where to start:
CppCMS - scalable MVC framework oriented for performance.
Wt - framework that mimics Qt for web (not sure how it scales well).
|
2,612,938 | 2,625,280 | Simplest way to get current time in current timezone using boost::date_time? | If I do date +%H-%M-%S on the commandline (Debian/Lenny), I get a user-friendly (not UTC, not DST-less, the time a normal person has on their wristwatch) time printed.
What's the simplest way to obtain the same thing with boost::date_time ?
If I do this:
std::ostringstream msg;
boost::local_time::local_date_time t =
boost::local_time::local_sec_clock::local_time(
boost::local_time::time_zone_ptr()
);
boost::local_time::local_time_facet* lf(
new boost::local_time::local_time_facet("%H-%M-%S")
);
msg.imbue(std::locale(msg.getloc(),lf));
msg << t;
Then msg.str() is an hour earlier than the time I want to see. I'm not sure whether this is because it's showing UTC or local timezone time without a DST correction (I'm in the UK).
What's the simplest way to modify the above to yield the DST corrected local timezone time ? I have an idea it involves boost::date_time:: c_local_adjustor but can't figure it out from the examples.
| This does what I want:
namespace pt = boost::posix_time;
std::ostringstream msg;
const pt::ptime now = pt::second_clock::local_time();
pt::time_facet*const f = new pt::time_facet("%H-%M-%S");
msg.imbue(std::locale(msg.getloc(),f));
msg << now;
|
2,612,961 | 2,612,979 | Template deduction for function based on its return type? | I'd like to be able to use template deduction to achieve the following:
GCPtr<A> ptr1 = GC::Allocate();
GCPtr<B> ptr2 = GC::Allocate();
instead of (what I currently have):
GCPtr<A> ptr1 = GC::Allocate<A>();
GCPtr<B> ptr2 = GC::Allocate<B>();
My current Allocate function looks like this:
class GC
{
public:
template <typename T>
static GCPtr<T> Allocate();
};
Would this be possible to knock off the extra <A> and <B>?
| That cannot be done. The return type does not take part in type deduction, it is rather a result of having already matched the appropriate template signature. You can, nevertheless, hide it from most uses as:
// helper
template <typename T>
void Allocate( GCPtr<T>& p ) {
p = GC::Allocate<T>();
}
int main()
{
GCPtr<A> p = 0;
Allocate(p);
}
Whether that syntax is actually any better or worse than the initial GCPtr<A> p = GC::Allocate<A>() is another question.
P.S. c++11 will allow you to skip one of the type declarations:
auto p = GC::Allocate<A>(); // p is of type GCPtr<A>
|
2,613,009 | 2,613,022 | All Audio frequencies | How can I get(Is it possible?) all audio frequencies are now playing in the system for writing some sound visualizer? Is there any library c++ or c#?
Thanks in advance
| Basic steps are:
apply window function to block of samples (e.g. 1024 samples, Hanning window)
perform real-to-complex FFT on windowed samples
take magnitude of each FFT output bin (sqrt(re * re + im * im))
identify peaks in resulting power spectrum estimate
the bin index of each peak corresponds to the frequency of that component
|
2,613,249 | 2,613,302 | How to integrate ANTLR (2.7) in Visual Studio 2005 (C++) build? | I have a project containing files generated from a .g file (antlr 2.7.x). The guy who wrote the whole thing has left me with it. Until now, I did not need to modify the grammar and all was fine. But now, I cannot continue without modifying the grammar (i.e. the .g-file).
I have the source code of the used antlr and the visual studio 2005 project. Unfortunately, the lexer and parser files are not generated prior to the build (in fact they are never generated) and that leads to my question: how do I generate these files whenever the grammar file is modified? Or in other words, how do I integrate antlr into visual studio?
| The ANTLR wiki has a few entries about Visual Studio integration:
VisualStudio C# Projects & C/C++ .rules Files for Visual Studio
How do I make ANTLRWorks and Visual Studio work together?
|
2,613,261 | 2,613,273 | Using library files in Linux | I'm trying to use some of the functions that are in the /lib/libproc-3.2.6.so library in my Ubuntu distribution.
I have downloaded and installed the header files and they are defined in my source files.
Currently, this is all I'm trying to do, just for starters...
proc_t **read_proc = readproctab(0);
But I get the following compiler error:
/tmp/cclqMImG.o: In function `Sysmon::initialise_sysmon()':
sysmon.cpp:(.text+0x494): undefined reference to `readproctab'
collect2: ld returned 1 exit status
I'm aware I'm probably doing some wrong with the command I'm using to compile it, but due to lack of experience I'm not sure what I'm doing wrong. This is the g++ command I'm using to compile my cpp file:
g++ -o sysmon.o sysmon.cpp `pkg-config --libs --cflags gtk+-2.0`
Can someone please give me some pointers as to where I'm going wrong.
| You are not linking your executable against libproc (that is a linker error message).
Try adding -lproc to the linker command.
|
2,613,387 | 2,613,393 | Casting pointer to object to void * in C++ | I've been reading StackOverflow too much and started doubting all the code I've ever written, I keep thinking "Is that undefined behavour?" even in code that has been working for ages.
So my question - Is it safe and well defined behavour to cast a pointer to an object (In this case abstract interface classes) to a void* and then later on cast them back to the original class and call method using them?
I'm fully aware that the code that does this is probably awful. I wouldn't even consider writing it like this now (this is old code which I don't really want to change), so I'm not looking for a discussion of better ways to do this. I already know how to write it better if I ever did this again. But if it's actually broken to rely on this in C++ then I'll have to look at changing the code, if it's merely awful code then changing it won't be a priority.
I would have had no doubts about something this simple a year or two ago but as my understanding of C++ increases I actually find I have more and more worries about code being safe under the standards even if it works perfectly well. Perhaps reading too much stack overflow is a bad thing for productivity sometimes :P
| You are safe.
From C++(0x) draft,
§5.2.9/13 (for static_cast):
A value of type pointer to object converted to “pointer to cv void” and back, possibly with different cv-qualification, shall have its original value.
§5.2.10/7 (for reinterpret_cast):
Converting an rvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value.
(Of course, casting to an unrelated class is undefined behavior.)
|
2,613,507 | 2,613,571 | what does this C++ line of code mean "sol<?=f((1<<n)-1,i,0)+abs(P[i])*price;" | Could anyone help me to understand following line of code:
sol< ?=f((1<< n)-1,i,0)+abs(P[i])*price;
I am studying an algorithm written using c++ and it has following operator < ?= . My problem is with understanding < ?= operator. Also when I compile this code using g++ compiler , it gives error message for above line of code line of code
following is the error message returned.
Hello.cpp: In function ‘int main()’:
Hello.cpp:115: error: ‘memset’ was not declared in this scope
Hello.cpp:142: error: expected primary-expression before ‘?’ token
Hello.cpp:142: error: expected primary-expression before ‘=’ token
Hello.cpp:142: error: expected ‘:’ before ‘;’ token
Hello.cpp:142: error: expected primary-expression before ‘;’ token
Maybe < ?= it is not a single operator, but I can not understand what exactly this line of code does.
Thanks in advance for the time you spent reading this post.
| It's a GNU extension. It's basically a "lower than" operator.
int a = 3;
a <?= 2;
cout << a << endl; // prints 2, because 2 < 3
a <?= 10;
cout << a << endl; // prints 2 as well, because 10 > 2
Read more here.
|
2,613,537 | 2,613,566 | std::map keys in C++ | I have a requirement to create two different maps in C++. The Key is of type CHAR* and the Value is a pointer to a struct. I am filling 2 maps with these pairs, in separate iterations. After creating both maps I need find all such instances in which the value of the string referenced by the CHAR* are same.
For this I am using the following code :
typedef struct _STRUCTTYPE
{
..
} STRUCTTYPE, *PSTRUCTTYPE;
typedef pair <CHAR *,PSTRUCTTYPE> kvpair;
..
CHAR *xyz;
PSTRUCTTYPE abc;
// after filling the information;
Map.insert (kvpair(xyz,abc));
// the above is repeated x times for the first map, and y times for the second map.
// after both are filled out;
std::map<CHAR *, PSTRUCTTYPE>::iterator Iter,findIter;
for (Iter=iteratedMap->begin();Iter!=iteratedMap->end();mapIterator++)
{
char *key = Iter->first;
printf("%s\n",key);
findIter=otherMap->find(key);
//printf("%u",findIter->second);
if (findIter!=otherMap->end())
{
printf("Match!\n");
}
}
The above code does not show any match, although the list of keys in both maps show obvious matches. My understanding is that the equals operator for CHAR * just equates the memory address of the pointers.
My question is, what should i do to alter the equals operator for this type of key or could I use a different datatype for the string?
|
My understanding is that the equals operator for CHAR* just equates the memory address of the pointers.
Your understanding is correct.
The easiest thing to do would be to use std::string as the key. That way you get comparisons for the actual string value working without much effort:
std::map<std::string, PSTRUCTTYPE> m;
PSTRUCTTYPE s = bar();
m.insert(std::make_pair("foo", s));
if(m.find("foo") != m.end()) {
// works now
}
Note that you might leak memory for your structs if you don't always delete them manually. If you can't store by value, consider using smart pointers instead.
Depending on your usecase, you don't have to neccessarily store pointers to the structs:
std::map<std::string, STRUCTTYPE> m;
m.insert(std::make_pair("foo", STRUCTTYPE(whatever)));
A final note: typedefing structs the way you are doing it is a C-ism, in C++ the following is sufficient:
typedef struct STRUCTTYPE {
// ...
} *PSTRUCTTYPE;
|
2,613,562 | 2,613,578 | Is this list-initialization of an array of unknown size valid in C++0x? | Is this list-initialization of an array of unknown size valid in C++0x?
int main() { int x[]{0, 1,2,3,4}; return x[0]; }
I believe it is valid, but would appreciate some confirmation.
If anyone could quote from the C++0x-FCD to support their case, it would be greatly appreciated.
Thanks!
| This goes from 8.5/16 first bullet to 8.5.4 list-initialization and from 8.5.4/3 third bullet to 8.5.1 aggregate initialization and then 8.5.1/4 says
An array of unknown size initialized with a brace-enclosed initializer-list containing n initializer-clauses, where shall be greater than zero, is defined as having elements
The only difference if the object is an array between = { ... } and { ... } is that the first is called copy-list-initialization and the second is called direct-list-initialization, so both are kinds of list-initialization. The elements of the array are copy-initialized from the elements of the initializer list in both cases.
Notice that there is a subtle difference between those forms if the array has a size and the list is empty, in which case 8.5.4 second bullet applies:
struct A {
explicit A();
};
A a[1]{}; // OK: explicit constructor can be used by direct initialization
A a[1] = {}; // ill-formed: copy initialization cannot use explicit constructor
This difference does not apply to lists that have content in which case third bullet applies again, though
struct A {
explicit A(int);
};
A a[1]{0}; // ill-formed: elements are copy initialized by 8.5.1
A a[1] = {0}; // ill-formed: same.
The FCD changed this compared to the previous draft, and initialization with an empty initializer list now always works even with explicit default constructors. This is because the FCD states that the elements are value-initialized, and value initialization doesn't care about explicitness since it doesn't do overload resolution on default constructors (it couldn't figure out better or worse matches anyway). The previous draft used normal overload resolution on the constructors and thus rejected explicit default constructors during copy initialization. This defect report did that change.
|
2,613,645 | 2,614,085 | C++ addition overload ambiguity | I am coming up against a vexing conundrum in my code base. I can't quite tell why my code generates this error, but (for example) std::string does not.
class String {
public:
String(const char*str);
friend String operator+ ( const String& lval, const char *rval );
friend String operator+ ( const char *lval, const String& rval );
String operator+ ( const String& rval );
};
The implementation of these is easy enough to imagine on your own.
My driver program contains the following:
String result, lval("left side "), rval("of string");
char lv[] = "right side ", rv[] = "of string";
result = lv + rval;
printf(result);
result = (lval + rv);
printf(result);
Which generates the following error in gcc 4.1.2:
driver.cpp:25: error: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
String.h:22: note: candidate 1: String operator+(const String&, const char*)
String.h:24: note: candidate 2: String String::operator+(const String&)
So far so good, right? Sadly, my String(const char *str) constructor is so handy to have as an implicit constructor, that using the explicit keyword to solve this would just cause a different pile of problems.
Moreover... std::string doesn't have to resort to this, and I can't figure out why. For example, in basic_string.h, they are declared as follows:
template<typename _CharT, typename _Traits, typename _Alloc>
basic_string<_CharT, _Traits, _Alloc>
operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
const basic_string<_CharT, _Traits, _Alloc>& __rhs)
template<typename _CharT, typename _Traits, typename _Alloc>
basic_string<_CharT,_Traits,_Alloc>
operator+(const _CharT* __lhs,
const basic_string<_CharT,_Traits,_Alloc>& __rhs);
and so on. The basic_string constructor is not declared explicit. How does this not cause the same error I'm getting, and how can I achieve the same behavior??
| The reason for the ambiguity is that one candidate function is better than another candidate function only if none of its parameters are a worse match than the parameters of the other. Consider your two functions:
friend String operator+(const String&, const char*); // (a)
String operator+(const String&); // (b)
You are calling operator+ with a String and a const char*.
The second argument, of type const char*, clearly matches (a) better than (b). It is an exact match for (a), but a user-defined conversion is required for (b).
Therefore, in order for there to be an ambiguity, the first argument must match (b) better than (a).
The String on the left-hand side of the call to operator+ is not const. Therefore, it matches (b), which is a non-const member function, better than (a), which takes a const String&.
Therefore, any of the following solutions would remove the ambiguity:
Change the member operator+ to be a const member function
Change the non-member operator+ to take a String& instead of a const String&
Call operator+ with a const String on the left hand side
Obviously, the first, also suggested by UncleBens, is the best way to go.
|
2,613,708 | 2,614,064 | Extracting public key from private key in OpenSSL | I need to extract the RSA public key from a RSA private key using OpenSSL.
I'm currently using RSAPublicKey_dup() passing the RSA* private key to get the public key. However, while the call seems to work, I cannot load (or use) this public key using the openssl command-line tool.
If I generate the public key using the command-line tool ("$ openssl rsa -in private.pem -pubout > public.pem"), I can use it and it works like a charm.
Do you guys know how I can get this work ? Maybe another function ? The OpenSSL documentation is quite hard to browse...
Thank you.
| I managed to make this work using PEM_write_bio_RSA_PUBKEY() to write the PEM data to a in-memory buffer, then using PEM_read_bio_RSA_PUBKEY() to get a new RSA*.
Now the generated public key can be used ;)
|
2,613,891 | 2,613,925 | Priority queue structure used? | While searching for some functions in C++ standard library documentation I read that push and pop for priority queues needs constant time.
http://www.cplusplus.com/reference/stl/priority_queue/push/
Constant (in the priority_queue). Although notice that push_heap operates in logarithmic time.
My question is what kind of data structure is used to maintain a priority queue with O(1) for push and pop ?
| I assume you are referring to cplusplus.com's page.
Earlier on the page it says:
This member function effectively calls the member function push_back of the underlying container object, and then calls the push_heap algorithm to keep the heap property of priority_queues.
So, after the O(1) push, the data structure has lost its heap property invariant and will then always follow that with an O(log N) call to restore that property. In other words, the O(1) operation is only one part of the entire operation; the full operation is O(1) + O(log N) which is the same as O(log N).
I guess the reason they mention that is that priority queue is an adapter and they are trying to emphasize the difference between what the underlying container does vs what the adapter does.
|
2,613,970 | 2,614,157 | calling std::cout.rdbuf() produces syntax error | Maybe I missed something, but I cant figure out why Visual Studio 2008 isn't seeing the rdbuf() procedure. Here is my code:
16. #include "DebugBuffer/BufferedStringBuf.h"
17.
18. BufferedStringBuf debug_buffer(256);
19. std::cout.rdbuf(&debug_buffer);
The BufferedStringBuf class is from this page: http://www.devmaster.net/forums/showthread.php?t=7037
Which produces the following error:
...src\main.cpp(19) : error C2143: syntax error : missing ';' before '.'
All I want to do is redirect std::cout to the Visual Studio Output window using OutputDebugString()..
| You're not allowed to have executable statements at file-level scope. You can declare variables, but you can't call functions as standalone statements. Move your code into a function (such as gf's answer demonstrates), and you should have no problem.
|
2,614,113 | 2,614,290 | Return a dynamic string from std::exception's `what` | I'm convinced at this point that I should be creating subclasses of std::exception for all my exception throwing needs. Now I'm looking at how to override the what method.
The situation that I'm facing, it would be really handy if the string what returns be dynamic. Some pieces of code parse an XML file for example, and adding a position or line number to the error message is useful to me.
I am trying to follow the Boost Exception handling guidelines.
What I'd like to know:
what returns a const char *, which implies any catcher is likely not going to free the string. So I need some other place to store the result, but where would that be? (I need thread-safety.)
what also includes throw() in its signature. While I can prevent my what from throwing anything, it seems to me that this method really isn't intended for anything too dynamic. If what is not the right place, then where should I be doing this instead?
From the answers I've gotten so far, it looks like the only way to accomplish this is by storing the string in the exception. The Boost guidelines recommend against this, which is confusing to me, because std::runtime_error does just that.
Even if I were to use a C-string, I'd have to use a statically sized buffer, or do memory management which can fail too. (I'm wondering if this is actually the only thing that can go wrong in std::string's copy-constructor. That would mean I won't gain anything using dynamically allocated C-strings.)
Is there any other option left?
| My exception classes generally don't have anything but the constructor and look along these lines:
class MyEx: public std::runtime_error
{
public:
MyEx(const std::string& msg, int line):
std::runtime_error(msg + " on line " + boost::lexical_cast<string>(line))
{}
};
An arbitrary example, but it is the base class that handles managing the what() message.
But if you want to, you can also only assign the base part of the exception object, after you've put together the message in the constructor body.
#include <stdexcept>
#include <string>
#include <sstream>
class MyEx: public std::runtime_error
{
public:
MyEx(const std::string& msg, int line):
std::runtime_error("")
{
std::stringstream ss;
ss << msg << " on line " << line;
static_cast<std::runtime_error&>(*this) = std::runtime_error(ss.str());
}
};
#include <iostream>
int main()
{
try {
throw MyEx("Evil code", __LINE__);
}
catch (const std::exception& e) {
std::cout << e.what() << '\n';
}
}
However, regarding the boost's guidelines, perhaps you should pay attention to the point that numeric data (positions and lines) might best be made available as numbers through other methods. The guidelines say to worry less about the what() message.
|
2,614,306 | 2,614,366 | Modifying text files and executing programs with command line parameters in c# or c++ on Linux | I have a need to create a utility in Suze Linux. The utility will make modifications to some text files, and then use the information in those text files to program a device in the computer using a different executable which accepts command line parameters.
I am fluent in c#, but have never worked with Linux. Should I take the time to learn Gnu C++ to do this, or install Mono? How would I execute the programming utility and pass it command line parameters?
| Is there a reason you want to restrict yourself to only C++ or C#? There are many options you could consider, for example:
For very simple tasks:
Bash: In some cases a simple Bash script will be able to solve the task. Piping information from one process to another is a breeze, and you have the power of sed, awk, etc. at your fingertips. Another major advantage is that it is installed almost everywhere.
For slightly more involved tasks you could try a scripting language:
Python: Easy to learn, pleasant to read. Very useful for putting together small applications quickly. You can use subprocess to communicate with other processes.
Ruby: Similar comments to Python - a good scripting language with a clean syntax.
Perl: Perl is very good at processing text, although personally I dislike the syntax.
Other options:
Java: Your C# experience will allow you to learn Java quickly as it is a very similar language. Java is officially supported on Linux.
C#: A lot of Linux users are wary of C# because it isn't free enough, but obviously that isn't a worry for you. It has worked fine the few times I've tried it. Note that Mono is not 100% compatible with Microsoft's version.
C++: For what you're planning to do I personally wouldn't recommend C++. It will solve the task though, and if you already know some C++ then I guess it is worth considering.
Obviously there are many other suitable options too.
|
2,614,314 | 2,614,373 | When to use a namespace or a struct? | I was just reading a little bit on them from http://www.cplusplus.com/doc/tutorial/namespaces/
and it seems like a struct is capable of the same things? Or even a class for that matter. Maybe someone here can better define what a namespace is, and how it differs from a struct/class?
| Namespaces and class-types are not capable of the same things. Namespaces are mainly used to group types and functions together to avoid name collisions, while class-types hold data and operations that work on that data.
To just group functions and objects by using a class-types you'd have to make them static:
struct X {
static void f();
};
Without static you'd have to create instances of the class-types to use them. A namespace is much better suited here:
namespace X {
void f();
}
Another important thing are using declarations and directives:
namespace X {
void f();
void g();
}
void h() {
using X::f;
f(); // f() now visible in current scope
using namespace X;
f(); g(); // both visible
}
With class-types there simply is no mechanism that allows that.
What class-types give you over namespaces is that you can have multiple instances with differing state - if you need that use a class-type.
|
2,614,428 | 2,614,451 | How to effectively measure difference in a run-time | One of the exercises in TC++PL asks:
Write a function that either returns a value or that throws that value based on an argument. Measure the difference in run-time between the two ways.
Great pity he never explaines how to measure such things. I'm not sure if I'm suppose to write simple "time start, time end" counter, or are there more effective and practical ways?
| For each of the functions,
Get the start time
Call the function a million times (or more... a million isn't that many, really)
Get the end time and subtract from it the start time
and compare the results. That's about as practical as performance measuring gets.
|
2,614,527 | 2,614,535 | How do I get the next token in a Cstring if I want to use it as an int? (c++) | My objective is to take directions from a user and eventually a text file to move a robot. The catch is that I must use Cstrings(such as char word[];) rather than the std::string and tokenize them for use.
the code looks like this:
void Navigator::manualDrive()
{
char uinput[1];
char delim[] = " ";
char *token;
cout << "Enter your directions below: \n";
cin.ignore();
cin.getline (uinput, 256);
token=strtok(uinput, delim);
if(token == "forward")
{
int inches;
inches=token+1;
travel(inches);
}
}
I've never used Cstrings I've never tokenized anything before, and I don't know how to write this. Our T.A.'s expect us to google and find all the answers because they are aware we've never been taught these methods. Everyone in my lab is having much more trouble than usual.
I don't know the code to write but I know what I want my program to do.
I want it to execute like this:
1) Ask for directions.
2) cin.getline the users input
3) tokenize the inputed string
4) if the first word token == "forward" move to the next token and find out how many inches to move forward then move forward
5) else if the first token == "turn" move to the next token. if the next token == "left" move to the next token and find out how many degrees to turn left
I will have to do this for forward x, backward x, turn left x, turn right x, and stop(where x is in inches or degrees). I already wrote functions that tell the robot how to move forward an inch and turn in degrees. I just need to know how to convert the inputted strings to all lowercase letters and move from token to token and convert or extract the numbers from the string to use them as integers.
If all is not clear you can read my lab write up at this link: http://www.cs.utk.edu/~cs102/robot_labs/Lab9.html
If anything is unclear please let me know, and I will clarify as best I can.
|
To convert to lower, you can use tolower. It operates one character at a time, so you need a simple loop.
To parse a string into an integer, you can use strtoll.
Move to the next token just means call strtok again (in this case inside an if statement).
|
2,614,809 | 2,614,902 | What is the default value for C++ class members | What is the default values for members of a struct and members of a class in c++, and how do these rules differ (e.g. between classes/structs/primitives/etc) ? Are there circumstances where the rules about the default values differs ?
| There are no differences between structs and classes in this regard in C++. They all are called just class types.
Members of class types have no default values in general case. In order to for a class member to get a deterministic value it has to be initialized, which can be done by
Default constructor of the member itself
Constructor initializer list of the enclosing class
Explicitly specified initializer for object of the enclosing class (that includes value-initialization and initialization with aggregate initializer).
Additionally, all objects with static storage duration are zero-initialized at the program startup.
Aside from the above cases, class members, once again, have no default values and will initially contain unpredictable garbage values.
|
2,614,836 | 2,614,916 | how to instantiate template of template | I have template that looks like this:
100 template<size_t A0, size_t A1, size_t A2, size_t A3>
101 struct mask {
103 template<size_t B0, size_t B1, size_t B2, size_t B3>
104 struct compare {
105 static const bool value = (A0 == B0 && A1 == B1 && A2 == B2 && A3 == B3);
106 };
107 };
...
120 const typename boost::enable_if_c<
121 mask<a,b,c,d>::compare<2,3,0,1>::value || ...>::type
I am trying to instantiate compare structure. How do I do get value in line 121?
| You probably need template before compare:
120 const typename boost::enable_if_c<
121 mask<a,b,c,d>::template compare<2,3,0,1>::value || ...>::type
|
2,614,895 | 2,615,023 | What library can I use to do simple, lightweight message passing? | I will be starting a project which requires communication between distributed nodes(the project is in C++). I need a lightweight message passing library to pass very simple messages(basically just strings of text) between nodes. The library must have the following characteristics:
No external setup required. I need to be able to get everything up-and-running in my code - I don't want to require the user to install any packages or edit any configuration files(other than a list of IP addresses and ports to connect to).
The underlying protocol which the library uses must be TCP(or if it is UDP, the library must guarantee the eventual receipt of the message).
The library must be able to send and receive arbitrarily large strings(think up to 3GB+).
The library needn't support any security mechanisms, fault tolerance, or encryption - I just need it to be fast, simple, and easy to use. I've considered MPI, but concluded it would require too much setup on the user's machine for my project.
What library would you recommend for such a project? I would roll my own, but due to time constraints, I don't think that will be feasible.
| Take a look at ØMQ, i.e. ZeroMQ.
|
2,615,012 | 2,615,035 | retrieve multiple display information using win32/C++ | Is there any way to retrieve information about how many extra displays there are besides the main one, how they are numbered, what the dimensions are, etc? I know this is pretty easy in .net land.
| EnumDisplayMonitors should get you started.
|
2,615,032 | 2,615,166 | How can I check the network connection type using the Windows API? | How can I programmatically retrieve the current connection type (eg. LAN or Direct connection)?
InternetGetConnectedState() isn't very reliable.
For instance, I'm connected to a wireless network, but ConTypeRet is 18, which is INTERNET_CONNECTION_LAN & INTERNET_RAS_INSTALLED. Isn't there any way to make sure that ConTypeRet is either INTERNET_CONNECTION_LAN or INTERNET_CONNECTION_MODEM?
| I'm confused by your "It is unreliable" statement. You can just check for both:
bool IsLanOrModem() {
DWORD result;
if (!InternetGetConnectedState(&result, 0))
throw GetLastError();
return result & INTERNET_CONNECTION_LAN || result & INTERNET_CONNECTION_MODEM;
}
|
2,615,071 | 2,615,245 | C++ How do you set an array of pointers to null in an initialiser list like way? | I am aware you cannot use an initialiser list for an array. However I have heard of ways that you can set an array of pointers to NULL in a way that is similar to an initialiser list.
I am not certain how this is done. I have heard that a pointer is set to NULL by default, though I do not know if this is guaranteed/ in the C++ standard. I am also not sure if initialising through the new operator compared to normal allocation can make a difference too.
Edit: I mean to do this in a header file/constructor initialisation list. I do not want to put it in the constructor, and I do not want to use a Vector.
| In order to set an array of pointers to nulls in constructor initializer list, you can use the () initializer
struct S {
int *a[100];
S() : a() {
// `a` contains null pointers
}
};
Unfortunately, in the current version of the language the () initializer is the only initializer that you can use with an array member in the constructor initializer list. But apparently this is what you need in your case.
The () has the same effect on arrays allocated with new[]
int **a = new int*[100]();
// `a[i]` contains null pointers
In other contexts you can use the {} aggregate initializer to achieve the same effect
int *a[100] = {};
// `a` contains null pointers
Note that there's absolutely no need to squeeze a 0 or a NULL between the {}. The empty pair of {} will do just fine.
|
2,615,078 | 2,615,092 | How to read in a double from a file in c++ | How do you read in a double from a file in C++?
For ints I know you can use the getline() and then atoi, but I am not finding an array to double function. What is available for reading in doubles, or converting a char array to a double?
| You can use stream extraction:
std::ifstream ifs(...);
double d;
ifs >> d;
This work provided that other then whitespace, the next data in the stream should be a double in textual representation.
After the extraction, you can check the state of the stream to see if there were errors:
ifs >> d;
if (!ifs)
{
// the double extraction failed
}
|
2,615,162 | 2,615,199 | How is its lifetime of a return value extended to the scope of the calling function when it is bound to a const reference in the calling function? | "If you return a value (not a reference) from the function, then bind it to a const reference in the calling function, its lifetime would be extended to the scope of the calling function."
So: CASE A
const BoundingBox Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
Returns a value of type const BoundingBox from function GetBoundingBox()
variant I: (Bind it to a const reference)
const BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
variant II: (Bind it to a const copy)
const BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
Both work fine and I don't see the l_Bbox object going out of scope. (Though, I understand in variant one, the copy constructor is not called and thus is slightly better than variant II).
Also, for comparison, I made the following changes.
CASE B
BoundingBox Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
with Variants:
I
BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
and II:
BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
The object l_Bbox still does not go out scope. How does "bind it to a const reference in the calling function, its lifetime would be extended to the scope of the calling function", really extend the lifetime of the object to the scope of the calling function ?
Am I missing something trivial here?
| Normally a temporary object (such as one returned by a function call) has a lifetime that extends to the end of the "enclosing expression". However, a temporary bound to a reference generally has it's lifetime 'promoted' to the lifetime of the reference (which may or may not be the lifetime of the calling function), but there are a couple exceptions. This is covered by the standard in 12.2/5 "Temporary objects":
The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.
See the following for more information:
C++ constant reference lifetime (container adaptor)
GotW #88: A Candidate For the "Most Important const"
An example that might help visualize what's going on:
#include <iostream>
#include <string>
class foo {
public:
foo( std::string const& n) : name(n) {
std::cout << "foo ctor - " << name + " created\n";
};
foo( foo const& other) : name( other.name + " copy") {
std::cout << "foo copy ctor - " << name + " created\n";
};
~foo() {
std::cout << name + " destroyed\n";
};
std::string getname() const { return name; };
foo getcopy() const { return foo( *this); };
private:
std::string name;
};
std::ostream& operator<<( std::ostream& strm, foo const& f) {
strm << f.getname();
return strm;
}
int main()
{
foo x( "x");
std::cout << x.getcopy() << std::endl;
std::cout << "note that the temp has already been destroyed\n\n\n";
foo const& ref( x.getcopy());
std::cout << ref << std::endl;
std::cout << "the temp won't be deleted until after this...\n\n";
std::cout << "note that the temp has *not* been destroyed yet...\n\n";
}
Which displays:
foo ctor - x created
foo copy ctor - x copy created
x copy
x copy destroyed
note that the temp has already been destroyed
foo copy ctor - x copy created
x copy
the temp won't be deleted until after this...
note that the temp has *not* been destroyed yet...
x copy destroyed
x destroyed
|
2,615,203 | 2,615,205 | Is sizeof in C++ evaluated at compilation time or run time? | For example result of this code snippet depends on which machine: the compiler machine or the machine executable file works?
sizeof(short int)
| sizeof is a compile time operator.
|
2,615,281 | 2,615,296 | What is the ISO C++ way to directly define a conversion function to reference to array? | According to the standard, a conversion function has a function-id operator conversion-type-id, which would look like, say, operator char(&)[4] I believe. But I cannot figure out where to put the function parameter list. gcc does not accept either of operator char(&())[4] or operator char(&)[4]() or anything I can think of.
Now, gcc seems to accept (&operator char ())[4] but clang does not, and I am inclined to not either, since it does not seem to fit the grammar as I understand it.
I do not want to use a typedef because I want to avoid polluting the namespace with it.
| You can use identity
template<typename T>
struct identity { typedef T type; };
struct sample {
operator identity<char[4]>::type &() {
...
}
};
You are correct that function and array declarators won't work in conversion functions. This is also known and discussed in this issue report. However i think that C++0x already provides a solution to what they discuss there
struct sample {
template<typename T>
using id = T;
template<typename T, int N>
operator id<T[N]> &() {
...
}
};
Unlike the identity and typedef approach, this allows T and N to be deduced, i think.
|
2,615,435 | 2,615,445 | No Matching Function Error for inserting into a list in c++ | I am getting an error when I try to insert an item into a list (in C++). The error is that there is no matching function for call to the insert(). I also tried push_front() but got the same error.
Here is the error message:
main.cpp:38: error: no matching function for call to ‘std::list<Salesperson, std::allocator<Salesperson> >::insert(Salesperson&)’
/usr/lib/gcc/i686-pc-cygwin/4.3.4/include/c++/bits/list.tcc:99: note: candidates are: std::_List_iterator<_Tp> std::list<_Tp, _Alloc>::insert(std::_List_iterator<_Tp>, const _Tp&) [with _Tp = Salesperson, _Alloc = std::allocator<Salesperson>]
/usr/lib/gcc/i686-pc-cygwin/4.3.4/include/c++/bits/stl_list.h:961: note: void std::list<_Tp, _Alloc>::insert(std::_List_iterator<_Tp>, size_t, const _Tp&) [with _Tp = Salesperson, _Alloc = std::allocator<Salesperson>]
Here is the code:
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include "Salesperson.h"
#include "Salesperson.cpp"
#include "OrderedList.h"
#include "OrderedList.cpp"
using namespace std;
int main(int argc, char** argv)
{
cout << "\n------------ Asn 8 - Sales Report ------------" << endl;
list<Salesperson> s;
int id;
string fName, lName;
int numOfSales;
string year;
std::ifstream input("Sales.txt");
while( !std::getline(input, year, ',').eof() )
{
input >> id;
input >> lName;
input >> fName;
input >> numOfSales;
Salesperson sp = Salesperson( id, fName, lName );
s.insert( sp ); //THIS IS LINE 38 **************************
//s.push_front( sp ); //ALSO GETS THE SAME ERROR
for( int i = 0; i < numOfSales; i++ )
{
double sale;
input >> sale;
sp.sales.insert( sale );
}
}
cout << endl;
return (EXIT_SUCCESS);
}
| insert needs both a position and an element - did you mean push_front or push_back?
|
2,615,905 | 2,616,076 | C++ template nontype parameter arithmetic | I am trying to specialize template the following way:
template<size_t _1,size_t _2> // workaround: bool consecutive = (_1 == _2 - 1)>
struct integral_index_ {};
...
template<size_t _1>
struct integral_index_<_1, _1 + 1> { // cannot do arithmetic?
//struct integral_index_<_1, _2, true> { workaround
};
however I get compiler message error
the template argument list of the partial specialization includes a non
-type argument whose type depends on a template parameter.
what do my doing wrong?
thanks
I put workaround in comments. Apparently I cannot do arithmetic in template specialization? seems counterintuitive.
here is my final solution in the problem to be solved. Basically, consecutive index requires one multiplication only.
130 template<size_t _1,size_t _2, bool consecutive = (_1 == _2 - 1)>
131 struct integral_index_ {
132 template<typename T, typename U>
133 __device__
134 static T eval(const T (&N)[4], const U &index) {
135 T j = index/N[_1];
136 return ((index - j*N[_1])*range<0,_1>::multiply(N) +
137 j*range<0,_2>::multiply(N));
138 }
139 };
140
141 template<size_t _1,size_t _2>
142 struct integral_index_<_1, _2, true> {
143 template<typename T, typename U>
144 __device__
145 static T eval(const T (&N)[4], const U &index) {
146 return index*range<0,_1>::multiply(N);
147 }
148 };
149
150 template<size_t _1,size_t _2, typename T, typename U>
151 __device__
152 T integral_index(const T (&N)[4], const U &index) {
153 return integral_index_<_1,_2>::eval(N, index);
154 }
| I am posting my solution is suggested by GMan
130 template<size_t _1,size_t _2, bool consecutive = (_1 == _2 - 1)>
131 struct integral_index_ {
132 template<typename T, typename U>
133 __device__
134 static T eval(const T (&N)[4], const U &index) {
135 T j = index/N[_1];
136 return ((index - j*N[_1])*range<0,_1>::multiply(N) +
137 j*range<0,_2>::multiply(N));
138 }
139 };
140
141 template<size_t _1,size_t _2>
142 struct integral_index_<_1, _2, true> {
143 template<typename T, typename U>
144 __device__
145 static T eval(const T (&N)[4], const U &index) {
146 return index*range<0,_1>::multiply(N);
147 }
148 };
149
150 template<size_t _1,size_t _2, typename T, typename U>
151 __device__
152 T integral_index(const T (&N)[4], const U &index) {
153 return integral_index_<_1,_2>::eval(N, index);
154 }
|
2,616,011 | 2,616,633 | Easy way to parse a url in C++ cross platform? | I need to parse a URL to get the protocol, host, path, and query in an application I am writing in C++. The application is intended to be cross-platform. I'm surprised I can't find anything that does this in the boost or POCO libraries. Is it somewhere obvious I'm not looking? Any suggestions on appropriate open source libs? Or is this something I just have to do my self? It's not super complicated but it seems like such a common task I am surprised there isn't a common solution.
| There is a library that's proposed for Boost inclusion and allows you to parse HTTP URI's easily. It uses Boost.Spirit and is also released under the Boost Software License. The library is cpp-netlib which you can find the documentation for at http://cpp-netlib.github.com/ -- you can download the latest release from http://github.com/cpp-netlib/cpp-netlib/downloads .
The relevant type you'll want to use is boost::network::http::uri and is documented here.
|
2,616,082 | 2,616,147 | How to properly use references with variadic templates | I have something like the following code:
template<typename T1, typename T2, typename T3, typename T4>
void inc(T1& t1, T2& t2, T3& t3, T4& t4) { ++t1; ++t2; ++t3; ++t4; }
template<typename T1, typename T2, typename T3>
void inc(T1& t1, T2& t2, T3& t3) { ++t1; ++t2; ++t3; }
template<typename T1, typename T2>
void inc(T1& t1, T2& t2) { ++t1; ++t2; }
template<typename T1>
void inc(T1& t1) { ++t1; }
I'd like to reimplement it using the proposed variadic templates from the upcoming standard. However all the examples I've seen so far online seem to be printf like examples, the difference here seems to be the use of references. I've come up with the following:
inline void inc() { }
template<typename T>
inline void inc(T&& t) { ++t; }
template<typename T,typename ... Args>
inline void inc(T&& t, Args&& ... args) { ++t; inc(args...); }
What I'd like to know is:
Should I be using r-values instead of references?
Possible hints or clues as to how to accomplish what I want correctly.
What guarantees does the new proposed standard provide in regard to the issue of the recursive function calls, is there some indication that the above variadic version will be as optimal as the original? (should I add inline or some-such?)
| I would not use rvalue references here, because that will allow you to bind to rvalues which can allow such nonsensical code as:
inc(1);
So, I would stick with regular references:
template<typename T>
void inc(T& t) { ++t; }
template<typename T,typename ... Args>
void inc(T& t, Args& ... args) { ++t; inc(args...); }
|
2,616,107 | 2,616,180 | Returning object from function | I am really confused now on how and which method to use to return object from a function. I want some feedback on the solutions for the given requirements.
Scenario A:
The returned object is to be stored in a variable which need not be modified during its lifetime. Thus,
const Foo SomeClass::GetFoo() {
return Foo();
}
invoked as:
someMethod() {
const Foo& l_Foo = someClassPInstance->GetFoo();
//...
}
Scneraio B:
The returned object is to be stored in a variable which will be modified during its lifetime. Thus,
void SomeClass::GetFoo(Foo& a_Foo_ref) {
a_Foo_ref = Foo();
}
invoked as:
someMethod() {
Foo l_Foo;
someClassPInstance->GetFoo(l_Foo);
//...
}
I have one question here: Lets say that Foo cannot have a default constructor. Then how would you deal with that in this situation, since we cant write this anymore:
Foo l_Foo
Scenario C:
Foo SomeClass::GetFoo() {
return Foo();
}
invoked as:
someMethod() {
Foo l_Foo = someClassPInstance->GetFoo();
//...
}
I think this is not the recommended approach since it would incur constructing extra temporaries.
What do you think ? Also, do you recommend a better way to handle this instead ?
| First, let's look into the things that come into play here:
(a) Extending lifetime of a temporary when it's used to initialize a reference - I learnt about it in this publication by Andrei Anexandrescu. Again, it feels weird but useful:
class Foo { ... }
Foo GetFoo() { return Foo(); } // returning temporary
void UseGetFoo()
{
Foo const & foo = GetFoo();
// ... rock'n'roll ...
foo.StillHere();
}
The rule says that when a reference is initialized with a temporary, the temporary's lifetime is extended until the reference goes out of scope. (this reply quotes the canon)
(b) Return Value Optimization - (wikipedia) - the two copies local --> return value --> local may be omitted under circumstances. That's a surprising rule, as it allows the compiler to change the observable behavior, but useful.
There you have it. C++ - weird but useful.
So looking at your scenarios
Scenario A: you are returning a temporary, and bind it to a reference - the temporary's lifetime is extended to the lifetime of l_Foo.
Note that this wouldn't work if GetFoo would return a reference rather than a temporary.
Scenario B: Works, except that it forces a Construct-Construct-Copy-Cycle (which may be much more expensive than single construct), and the problem you mention about requiring a default constructor.
I wouldn't use that pattern to create a object - only to mutate an existing one.
Scenario C: The copies of temporaries can be omitted by the compiler (as of RVO rule). There is unfortunately no guarantee - but modern compilers do implement RVO.
Rvalue references in C++ 0x allows Foo to implement a resource pilfering constructor that not only guarantees supression of the copies, but comes in handy in other scenarios as well.
(I doubt that there's a compiler that implements rvalue references but not RVO. However there are scenarios where RVO can't kick in.)
A question like this requires mentioning smart pointers, such as shared_ptr and unique_ptr (the latter being a "safe" auto_ptr). They are also in C++ 0x. They provide an alternate pattern for functions creating objects.
|
2,616,155 | 2,616,182 | C++ Class Access Specifier Verbosity | A "traditional" C++ class (just some random declarations) might resemble the following:
class Foo
{
public:
Foo();
explicit Foo(const std::string&);
~Foo();
enum FooState
{
Idle, Busy, Unknown
};
FooState GetState() const;
bool GetBar() const;
void SetBaz(int);
private:
struct FooPartialImpl;
void HelperFunction1();
void HelperFunction2();
void HelperFunction3();
FooPartialImpl* m_impl; // smart ptr
FooState m_state;
bool m_bar;
int m_baz;
};
I always found this type of access level specification ugly and difficult to follow if the original programmer didn't organize his "access regions" neatly.
Taking a look at the same snippet in a Java/C# style, we get:
class Foo
{
public: Foo();
public: explicit Foo(const std::string&);
public: ~Foo();
public: enum FooState
{
Idle, Busy, Unknown
};
public: FooState GetState() const;
public: bool GetBar() const;
public: void SetBaz(int);
private: struct FooPartialImpl;
private: void HelperFunction1();
private: void HelperFunction2();
private: void HelperFunction3();
private: FooPartialImpl* m_impl; // smart ptr
private: FooState m_state;
private: bool m_bar;
private: int m_baz;
};
In my opinion, this is much easier to read in a header because the access specifier is right next to the target, and not a bunch of lines away. I found this especially true when working with header-only template code that wasn't separated into the usual "*.hpp/*.inl" pair. In that scenario, the size of the function implementations overpowered this small but important information.
My question is simple and stems from the fact that I've never seen anyone else actively do this in their C++ code.
Assuming that I don't have a "Class View" capable IDE, are there any obvious drawbacks to using this level of verbosity?
Any other style recommendations are welcome!
| "When in Rome, do as the Romans do."
I, having spent a lot of time with Java, like the style of specifying access specifiers for every field and method separately. However when I am programming in C++, I always use the style shown in your first code snippet.
|
2,616,272 | 2,831,611 | What is the best way to make a schedule in MFC | I have a list of items that are each associated with a start and end time and date. What I want to do is, given a time and date range, display only the items that fall within that window, even partially.
What I'm doing is creating a CListCtrl with all the items in it and the CListCtrl is sorted by start time by default. But given a time range, I don't know how to search for the first item that is within the range.
Another problem with the list control is it displays as a list, whereas it would be nice if there was a control that could also show things that are concurrent side by side.
I'm doing this within a dialog application.
| You're asking for some very specific functionality. It sounds like you are either building a scheduling app or are trying to display a log of things that have happened in the past. This is called a Gantt Chart. You can buy Gannt Chart controls for MFC on the web. Google for some.
There's more to your question than just how to paint it; You cannot and should not be using a CListCtrl as your data structure. You seem to have an array of objects that are start & end times. For example:
struct Range {
int startTime;
int endTime;
};
std::vector<Range> events;
Once you have put your events into this simple vector, you will have to loop through all of the elements and compare the start/end times to see if they overlap the Range that you are considering:
typedef std::vector<Range> RangeVec;
typedef RangeVec::iterator RangeIter;
void is_between(int time, const Range& r)
{
return time >= r.start && time <= r.end;
}
void findRanges(RangeVec *matches, const RangeVec& input, const Range& query)
{
for (RangeIter it = input.begin(); it != input.end(); ++it) {
if (is_between(it.start, query) || is_between(it.end, query) ||
(it.start <= query.start && it.end >= query.end))
{
matches->push_back(*it);
}
}
You can now loop through your matches and display them however you want. If you are brave, it's rather easy to write a custom control with a subclassed CWnd::OnPaint() that just draws rectangles as long as your overlapped range representing each match.
|
2,616,643 | 2,617,049 | Is there a standard cyclic iterator in C++ | Based on the following question: Check if one string is a rotation of other string
I was thinking of making a cyclic iterator type that takes a range, and would be able to solve the above problem like so:
std::string s1 = "abc" ;
std::string s2 = "bca" ;
std::size_t n = 2; // number of cycles
cyclic_iterator it(s2.begin(),s2.end(),n);
cyclic_iterator end;
if (std::search(it, end, s1.begin(),s1.end()) != end)
{
std::cout << "s1 is a rotation of s2" << std::endl;
}
My question, Is there already something like this available? I've checked Boost and STL and neither have an exact implementation.
I've got a simple hand-written (derived from a std::forward_iterator_tag specialised version of std::iterator) one but would rather use an already made/tested implementation.
| There is nothing like this in the standard. Cycles don't play well with C++ iterators because a sequence representing the entire cycle would have first == last and hence be the empty sequence.
Possibly you could introduce some state into the iterator, a Boolean flag to represent "not done yet." The flag participates in comparison. Set it true before iterating and to false upon increment/decrement.
But it might just be better to manually write the algorithms you need. Once you've managed to represent the whole cycle, representing an empty sequence might have become impossible.
EDIT: Now I notice that you specified the number of cycles. That makes a big difference.
template< class I >
class cyclic_iterator
/* : public iterator< bidirectional, yadda yadda > */ {
I it, beg, end;
int cnt;
cyclic_iterator( int c, I f, I l )
: it( f ), beg( f ), end( l ), cnt( c ) {}
public:
cyclic_iterator() : it(), beg(), end(), cnt() {}
cyclic_iterator &operator++() {
++ it;
if ( it == end ) {
++ cnt;
it = beg;
}
} // etc for --, post-operations
friend bool operator==
( cyclic_iterator const &lhs, cyclic_iterator const &rhs )
{ return lhs.it == rhs.it && lhs.cnt == rhs.cnt; } // etc for !=
friend pair< cyclic_iterator, cyclic_iterator > cycle_range
( int c, I f, I l ) {//factory function, better style outside this scope
return make_pair( cyclic_iterator( 0, f, l ),
cyclic_iterator( c, f, l ) );
}
};
|
2,616,709 | 2,616,760 | Launch a QWidget from a QMain window | I'm doing my first C++ - Qt4 application and I'm having some trouble "connecting" my different uis.
I have a main window with several buttons and when I click on one, I want another window to open.
The MyMainWindowClass inherits from QMainWindow and the other from QWidget.
Here is the code I have written so far :
#include <iostream>
#include "MyWidgetClass.hpp"
#include "MyMainWindowClass.hpp"
#include "ui_MyMainWindowClassUi.h"
MyMainWindowClass::MyMainWindowClass(QWidget *parent) :
QMainWindow(parent),
m_ui(new Ui::MyMainWindowClassUi)
{
m_ui->setupUi(this);
initConnect();
}
void MyMainWindowClass::initConnect()
{
QObject::connect(m_ui->SomeBtn,
SIGNAL(clicked()),
this,
SLOT(SomeBtnClicked()));
// Some other QObject::connect calls
return;
}
void MyMainWindowClass::SomeBtnClicked()
{
std::cout << "Some Btn has been clicked" << std::endl;
this->setEnabled(false);
MyWidgetClass mwc(this);
mwc.show();
return;
}
This calls the Ctor and the Dtor from MyWidgetClass, disables the MyMainWindowClassUi, but doesn't show my other GUI. What am I missing to have the window showed when I click on the button ?
| Try this instead of your SomeBtnClicked method:
MyWidgetClass *mwc;
void MyMainWindowClass::SomeBtnClicked()
{
std::cout << "Some Btn has been clicked" << std::endl;
this->setEnabled(false);
if (!mwc)
mwc = new MyWidgetClass(this);
mwc->show();
mwc->raise();
mwc->setActiveWindow(); // Qt 4: activateWindow()
return;
}
|
2,616,786 | 2,616,793 | Using stack defined in C++ stl | #include <stack>
using namespace std;
int main() {
stack<int> s;
int i;
for (i = 0; i <= 10; i++) {
s.push(i);
}
for (i = 0; i <= 10; i++) {
printf("%d", s.pop());
}
}
Whats wrong with the code above?
Error:
In function int main(): aggregate value used where an integer was expected
| stack::pop is a void function which just discards the top element on the stack, in order to get the value you want to use stack::top.
The reason this is so is for exception safety reasons (what happens if the object returned throws an exception in its copy constructor?).
|
2,616,804 | 2,616,823 | Accessing elements of an array defined in a class (C++) | Assume that int array arrayName is a member of class className, How can I access its element in my main program?? className.arrayName[0] doesn't seem to work
| If arrayName is static inside class className, then you can access it like that:
//Declaration
class className{
public:
static int arrayName[5];
};
//Access
className::arrayName[index];
If it is not static, you must create an instance of your class first.
//Declaration
class className{
public:
int arrayName[5];
};
//Access
className a;
a.arrayName[index];
|
2,616,832 | 2,616,835 | Does this mimic perfectly a function template specialization? | Since the function template in the following code is a member of a class template, it can't be specialized without specializing the enclosing class.
But if the compiler's full optimizations are on (assume Visual Studio 2010), will the if-else-statement in the following code get optimized out? And if it does, wouldn't it mean that for all practical purposes this IS a function template specialization without any performance cost?
template<typename T>
struct Holder
{
T data;
template<int Number>
void saveReciprocalOf();
};
template<typename T>
template<int Number>
void Holder<T>::saveReciprocalOf()
{
//Will this if-else-statement get completely optimized out
if(Number == 0) data = (T)0;
else data = (T)1 / Number;
}
//-----------------------------------
void main()
{
Holder<float> holder;
holder.saveReciprocalOf<2>();
cout << holder.data << endl;
}
| Chances are it will be optimized. But if you want to be sure you can use a compile-time if by using templates, e.g. Boost’s MPL if_ implementation.
Or you can use SFINAE (Boost.enable_if).
|
2,616,906 | 2,616,912 | How do I output coloured text to a Linux terminal? | How do I print coloured characters to a Linux terminal that supports it?
How do I tell whether the terminal supports colour codes?
| You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.
Example:
cout << "\033[1;31mbold red text\033[0m\n";
Here, \033 is the ESC character, ASCII 27. It is followed by [, then zero or more numbers separated by ;, and finally the letter m. The numbers describe the colour and format to switch to from that point onwards.
The codes for foreground and background colours are:
foreground background
black 30 40
red 31 41
green 32 42
yellow 33 43
blue 34 44
magenta 35 45
cyan 36 46
white 37 47
Additionally, you can use these:
reset 0 (everything back to normal)
bold/bright 1 (often a brighter shade of the same colour)
underline 4
inverse 7 (swap foreground and background colours)
bold/bright off 21
underline off 24
inverse off 27
See the table on Wikipedia for other, less widely supported codes.
To determine whether your terminal supports colour sequences, read the value of the TERM environment variable. It should specify the particular terminal type used (e.g. vt100, gnome-terminal, xterm, screen, ...). Then look that up in the terminfo database; check the colors capability.
|
2,616,968 | 2,616,977 | How to read and write a STL C++ string? | #include<string>
...
string in;
//How do I store a string from stdin to in?
//
//gets(in) - 16 cannot convert `std::string' to `char*' for argument `1' to
//char* gets (char*)'
//
//scanf("%s",in) also gives some weird error
Similarly, how do I write out in to stdout or to a file??
| You are trying to mix C style I/O with C++ types. When using C++ you should use the std::cin and std::cout streams for console input and output.
#include <string>
#include <iostream>
...
std::string in;
std::string out("hello world");
std::cin >> in;
std::cout << out;
But when reading a string std::cin stops reading as soon as it encounters a space or new line. You may want to use std::getline to get a entire line of input from the console.
std::getline(std::cin, in);
You use the same methods with a file (when dealing with non binary data).
std::ofstream ofs("myfile.txt");
ofs << myString;
|
2,617,123 | 2,617,462 | Library to analyse sound | I need in analyzing system output sound runtime. OS: Linux. The first thing I need is get different frequency values. Programming language: c++.
| One semi-portable* way that comes to mind for grabbing all the sound from multiple sources is PulseAudio. (In this case, semi-portable means working with many sound cards, not working with different OSes, though there is a WinXP version of PulseAudio). One of the PulseAudio modules provides a pipe sink. Hopefully all your outputs will be PulseAudio-compatible - nearly everything that plays nice with ALSA should be fine. You should then be able to just read from that pipe to get your input.
You can then use a library like FFTW (first suggested by Thomas' answer) for fast Fourier transform, assuming this is what you mean by 'get the frequency values'.
*In this case, semi-portable means working with many sound cards, not working with different OSes, though there is a WinXP version of PulseAudio (haven't tried it myself).
|
2,617,142 | 2,617,219 | Should it be in a namespace? | Do I have to put code from .cpp in a namespace from corresponding .h or it's enough to just write using declaration?
//file .h
namespace a
{
/*interface*/
class my
{
};
}
//file .cpp
using a::my; // Can I just write in this file this declaration and
// after that start to write implementation, or
// should I write:
namespace a //everything in a namespace now
{
//Implementation goes here
}
Thanks.
| I consider more appropriate to surround all the code that is meant to be in the namespace within a namespace a { ... } block, as that is semantically what you are doing: you are defining elements within the a namespace. But if you are only defining members then both things will work.
When the compiler finds void my::foo(), it will try to determine what my is, and it will find the using a::my, resolve my from that and understand that you are defining the a::my::foo method.
On the other hand this approach will fail if you are using free functions:
// header
namespace a {
class my { // ...
};
std::ostream & operator<<( std::ostream& o, my const & m );
}
// cpp
using a::my;
using std;
ostream & operator<<( ostream & o, my const & m ) {
//....
}
The compiler will happily translate the above code into a program, but what it is actually doing is declaring std::ostream& a::operator<<( std::ostream&, a::my const & ) in the header file --without implementation--, and defining std::ostream& ::operator<<( std::ostream &, a::my const & ) in the cpp file, which is a different function. Using Koening lookup, whenever the compiler sees cout << obj with obj of type a::my, the compiler will look in the enclosing namespaces of cout and my (std, and a) and will find that there is an a::operator<< declared but never defined in namespace a. It will compile but not link your code.
|
2,617,247 | 2,617,259 | C++ compile time polymorphism doubt? | Below program contains two show() functions in parent and child classes, but first show() function takes FLOAT argument and second show() function takes INT argument.
.If I call show(10.1234) function by passing float argument, it should call class A's show(float a) function , but it calls class B's show(int b).
#include<iostream>
using namespace std;
class A{
float a;
public:
void show(float a)
{
this->a = a;
cout<<"\n A's show() function called : "<<this->a<<endl;
}
};
class B : public A{
int b;
public:
void show(int b)
{
this->b = b;
cout<<"\n B's show() function called : "<<this->b<<endl;
}
};
int main()
{
float i=10.1234;
B Bobject;
Bobject.show((float) i);
return 0;
}
Output:
B's show() function called : 10
Expected output:
A's show() function called : 10.1234
Why g++ compiler chosen wrong show() function i.e class B's show(int b) function ?
| If you have a function in a derived class that has the same name as a function in the base class, it hides all of the functions in the base class. You either need to rename your function, or use a using declaration in your derived class:
using A::show;
or, you can explicitly call the base class function:
Bobject.A::show(i);
|
2,617,313 | 2,617,446 | How to call Java method from C++ | I am using JNI to call my C++ function from Java. One of the C++ function's arguments is jobject thiz (as far as I know, all JNI native functions have this argument). The function takes quite long to complete and I want to report progress back to the jobject thiz Java object, so that I can show the progress to the user. How can I call jobject's methods from C++?
| You need to look at the JNI functions GetMethodID and Call<type>Method*.
The details of the various variants and how to call them are documented the JNI specification.
|
2,617,359 | 8,537,887 | cross platform keyboard/mouse input recommendation | Does anyone have any suggestions for a good cross platform input library?
I'd like to get:
* at least keyboard and mouse input
* on at least the big three operating systems
* Small/fast
* C or C++
* permissive licensing gpl2/mit/free/etc.
So far I've seen:
* OIS (used in Ogre) http://sourceforge.net/projects/wgois/
* SDL (used everywhere it seems, might be a clue) http://www.libsdl.org/index.php
* Allegro http://www.talula.demon.co.uk/allegro/readme.html
Has any one used any of these, or know of something else that might be good?
Thanks
| I ended up using the Qt framework for this.
It's very complete, well supported, has a lot of features, and has better licensing now. It was possible to use it with the Ogre3d library so it worked out well for me. I also found that it's being used by the City of Heroes MMO for their user interface.
|
2,617,453 | 2,617,512 | Controlling shell command line wildcard expansion in C or C++ | I'm writing a program, foo, in C++. It's typically invoked on the command line like this:
foo *.txt
My main() receives the arguments in the normal way. On many systems, argv[1] is literally *.txt, and I have to call system routines to do the wildcard expansion. On Unix systems, however, the shell expands the wildcard before invoking my program, and all of the matching filenames will be in argv.
Suppose I wanted to add a switch to foo that causes it to recurse into subdirectories.
foo -a *.txt
would process all text files in the current directory and all of its subdirectories.
I don't see how this is done, since, by the time my program gets a chance to see the -a, then shell has already done the expansion and the user's *.txt input is lost. Yet there are common Unix programs that work this way. How do they do it?
In Unix land, how can I control the wildcard expansion?
(Recursing through subdirectories is just one example. Ideally, I'm trying to understand the general solution to controlling the wildcard expansion.)
| You program has no influence over the shell's command line expansion. Which program will be called is determined after all the expansion is done, so it's already too late to change anything about the expansion programmatically.
The user calling your program, on the other hand, has the possibility to create whatever command line he likes. Shells allow you to easily prevent wildcard expansion, usually by putting the argument in single quotes:
program -a '*.txt'
If your program is called like that it will receive two parameters -a and *.txt.
On Unix, you should just leave it to the user to manually prevent wildcard expansion if it is not desired.
|
2,617,455 | 2,617,473 | error with io stream | What is the problem with the last two statements in the code?
#include <iostream>
using namespace std;
int main()
{
cout << "2 + 4 = " << 2 + 4 << endl;
cout << "2 * 4 = " << 2 * 4 << endl;
cout << "2 | 4 = " << 2 | 4 << endl;
cout << "2 & 4 = " << 2 & 4 << endl;
What should I do to fix this?
|
What is the problem with the last two statements in the code?
Operator precedence. | and & have lower precedence than <<, so cout << "2 & 4 = " << 2 & 4 << endl; gets parsed as (cout << "2 & 4 = " << 2) & (4 << endl;).
What should I do to fix this?
Put parens around 2 | 4 and 2 & 4.
|
2,617,468 | 2,617,558 | Are there any way to link my program with Wine-compiled part? | I am trying to use windows dll functionality in Linux.
My current solution is a compilation of a separate wine application, that uses dll and transfer requests/responses between dll and main application over IPC.
This works, but is a real overhead comparing to a simple dll calls.
I see that wine-compiled program usually is a bootstrapping-script and some .so, which (according to file utility) is normal linux dynamically linked library.
Are there any way to link that .so directly to my application? Are there any manual?
| You may be able to use Winelib to write a Linux app that can use Windows DLLs.
EDIT:
For future reference:
libtest.c:
#include <stdio.h>
#include <windows.h>
int main(int argc, char* argv[])
{
HMODULE h;
h = LoadLibrary("cards.dll");
printf("%d\n", h);
}
Execution:
$ winegcc -m32 libtest.c
$ ./a.out
536936448
|
2,617,515 | 2,618,789 | Recommendation for a HTTP parsing library in C/C++ | I am looking for HTTP parsing library for C/C++.
I have looked curl library, but it seems it is a http client library.
I am looking for a library which parses HTTP header (e.g. a way to
get the query string, get cookie, get request url, get Post Data)?
Thank you.
| Check out libebb, it has a parser generated with Ragel using the easy yet powerful PEG (it's based on Zed Shaw's mongrel parser)
libebb is a lightweight HTTP server library for C. It lays the
foundation for writing a web server by providing the socket juggling
and request parsing. By implementing the HTTP/1.1 grammar provided
in RFC2612, libebb understands most most valid HTTP/1.1 connections
(persistent, pipelined, and chunked requests included) and rejects
invalid or malicious requests. libebb supports SSL over HTTP.
Also check this speedy parser
|
2,617,570 | 2,617,729 | How to use SAPI's SetNotifyCallbackFunction() in a CLR project with Windows Form as the interface window? | I'm trying to write a dll plugin for Winamp. I'm using Microsoft Visual Studio 2008 and Microsoft SAPI 5.1. I created the interface window using Windows Form (System::Windows::Forms::Form).
I tried to use SetNotifyWIndowMessage(), but the method is never called when I speak to the microphone. So I tried using SetNotifyCallbackFunction(), but I got a compile error saying that I should use '&' in front of the method name in the parameter. However, when I add the '&', I got another compile error saying that i can't take the address of the method unless creating delegate instance.
What should I do? Someone please help me..
| Well, as indicated, you need to create a delegate instance to wrap your callback. But don't go there, SAPI 5.1 is quite outdated. Updates are no longer shipped because the .NET framework has a very nice wrapper for it. Check out the System.Speech.Recognition namespace and the SpeechRecognitionEngine class. You'll want to use the SpeechRegonized event. You'll find plenty of code samples in the MSDN Library pages for the class.
|
2,617,868 | 2,661,032 | Warning: System.Web.dll built without parts that depend on: System.Web.Services.dll Mono.Web.dll | I am building mono (2.6.3) on Ubuntu 9.10
I am getting the following error:
Warning: System.Web.dll built without parts that depend on: System.Web.Services.dll Mono.Web.dll
Does anyone know what is causing this, and how I may resolve this?
| System.Web.dll contains a cyclic dependency on System.Web.Services.dll.
So what happens is Mono builds a version of System.Web that does not depend on S.W.S, then uses that to build S.W.S, and finally builds the final System.Web which replaces the first one.
This probably should not use the word warning. It is just the way things are, and it cannot be resolved.
|
2,617,884 | 2,618,221 | Is there a c++ library that provides functionality to execute an external program and read its output? | Basically, I'm looking for something that will allow me to replicate the following Perl code:
my $fh = new FileHandle;
$fh->open("foo |");
while (<$fh>) {
# Do something with this line of data.
}
This is in the context of Linux, so a library that is specific to Windows will not help. I know how to write a program that does fork/exec/dup2 and all that basic shell-type jazz, but there are some fiddly details involving terminals that I don't feel like messing around with (and I don't have a copy of "Advanced Programming in the UNIX Environment" or a similar reference handy), so I'm hoping that someone has already solved this problem.
| #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
char c;
FILE* p;
p = popen("echo hello, world!", "r");
if( p == NULL ) {
fprintf(stderr, "Failed to execute shell with \"echo hello, world!\"");
exit(1);
}
while( (c = fgetc(p)) != EOF ) {
fputc(toupper(c), stdout);
}
pclose(p);
return EXIT_SUCCESS;
}
|
2,617,887 | 2,618,698 | Qt Graphics Scene mouse event propagation | hello i'm learning qt and i'm doing the folowing to add some widgets to a graphics scene
void MainWindow::addWidgets(QList<QWidget *> &list, int code)
{
if(code == CODE_INFO)
{
QWidget *layoutWidget = new QWidget();
QVBoxLayout *layout = new QVBoxLayout();
foreach(QWidget *w, list)
{
layout->addWidget(w);
this->connect(((ProductInfo*)w), SIGNAL(productClicked()), this, SLOT(getProductDetails()));
}
layoutWidget->setLayout(layout);
this->scene->addWidget(layoutWidget);
}
}
my ProductInfo class processes mouse release and emits a signal
void ProductInfo::mouseReleaseEvent(QMouseEvent *e)
{
QWidget::mouseReleaseEvent(e);
emit productClicked();
}
the problem is after adding the widgets to the scene they no longer get the mouse release event and don't emit productClicked signal but if i add them to the main window(not to the scene) they work as expected. What am i doing wrong?
| I believe you should be able to get mouseReleaseEvent sent to your widget by QGraphicsScene if would add mousePressEvent event handler and call accept() for the event object there. Smth. like this:
void ProductInfo::mousePressEvent(QMouseEvent* event)
{
QWidget::mousePressEvent(event);
event->accept();
}
hope this helps, regards
|
2,617,907 | 2,666,007 | using 9 function of 21h interrupt in c++ | function 09h interrupts 21h
dx = offset of the text , ds = segment of the text
how can i obtain segment and offset in c++?
| #include <dos.h>
FP_SEG(&var);
returns segment of var
FP_OFF(&var);
returns offset of var
|
2,618,138 | 2,618,148 | Introduction to C# for C/C++ users | I have 6+ years of C/C++ experience. Tomorrow starts a university assignment where I will have to use C#. Therefore I would like to have a list of links/resources which you think important or an extensive tutorial - in short everything you think worthy.
Coding style, best practices, ...
(I don't know any specifics about the C# environment I will be using(IDE, OS, w/e), the first meeting is tomorrow evening).
(I have never coded C# before)
One more thing: I would like to work using Linux (kubuntu 10.4). IDE / environment / tutorial suggestions regarding Linux specifically are very welcome.
Thanks for your help!
| Charles Petzold has: .NET book zero
|
2,618,199 | 2,618,232 | Run function on running application on execute | Alright so what I am trying to do is essentially create a program that, when it is already executed, can be "executed" again, detect the already existing process and instead of creating another process, execute a function in the existing process.
Any ideas?
It's possible I am going at this all wrong. I am trying to adapt this open-source Virtual Printer (http://sourceforge.net/projects/imageprinter/) to an application of mine. The printer prints for example a PDF to a file and it seems also has a feature to launch an application. I need to grab the PDF into my own application for handling at this point and the user needs to be able to append more pdfs by printing them to this printer.
The way I was planning to handle it is to have the application check that folder for new files everytime it opens and a command is called when a new file is printed. Is there another way to import the pdf data more directly to a running process?
| 1: The typical solution is to use a named mutex for this. See this question asked on MSDN for more details.
2: Use one of these functions (maybe FindWindowEx?) and (if needed) some way to get the information for locating the HWND between the two processes. Sorry I can't be more clear, there are way too many ways to do this and it varies from application to application.
3: After you know the other application is running, you can use SendMessage with your own UINT message (make sure it doesn't clash with an existing message) and make sure to handle the special message in your message loop.
|
2,618,285 | 2,618,860 | C++ thread to separate process | Is there any way I can have a thread branch off into its own independent process? I know there's the CreateProcess function but as far as I can tell, you can only run external applications with it. Is what I'm asking for at all possible?
| It is possible.
You could call CreateProcess with a dummy application and with the CREATE_SUSPENDED flag so it doesn't run immediately. Then you can use VirtualAllocEx to allocate memory space in the created process and WriteProcessMemory to write code and data into it. And then unsuspend the process to run it.
You can also use CreateRemoteThread to create a process running within the context of another existing process.
So what you want to do is possible, but it's really not a simple thing to do in a windows environment so you'd have to have a really good reason to want to do it.
|
2,618,414 | 2,618,444 | Convert an int to a QString with zero padding (leading zeroes) | I want to "stringify" a number and add zero-padding, like how printf("%05d") would add leading zeros if the number is less than 5 digits.
| Use this:
QString number = QStringLiteral("%1").arg(yourNumber, 5, 10, QLatin1Char('0'));
5 here corresponds to 5 in printf("%05d"). 10 is the radix, you can put 16 to print the number in hex.
|
2,618,494 | 2,618,613 | C++ compilers and back/front ends | For my own education I am curious what compilers use which C++ front-end and back-end.
Can you enlighten me where the following technologies are used and what hallmarks/advantages they have if any?
Open64 - is it back-end, front-end, or both? Which compilers use it? I encounter it in CUDA compiler.
EDG - as far as I can tell this is a front-end use by Intel compilers and Comeau. do other compilers use it? I found quite a few references to it in boost source code.
ANTLR - this is general parser. Do any common compilers use it?
Regarding compilers:
with front-end/back-end does gcc compiler suite uses? does it have common heritage with any other compiler?
what front-end/back-end PGI and PathScale compilers use?
what front-end/back-end XL compiler uses (IBM offering).
in-depth links on the Internet or your personal know-how would be great.
I did some Google searching, but information I generally encountered was rather superficial.
Thanks.
| EDG is a front-end used by Intel and Comeau. See EDG's list of customers for other users.
ANTLR is a parser generator. I'm not aware of any C++ compiler built around a parser that was built with ANTLR (that doesn't mean it couldn't exist though).
GCC is a suite of compilers, with front ends for C, C++, Fortran, Ada, Java, etc., and back-ends for more processors than I'd care to think about.
Open64 is also a suite of compilers including several front-ends (for C, C++, Fortran, and possibly others I don't remember at the moment) and back-ends (targeting X64, Itanium, ARM, and, again, probably others I don't remember and/or don't know about). I believe its origin (pun noted by not intended) is SGI's compiler(s). I seem to remember reading something hinting that Open64 was derived from some version of the GCC front end(s), but offhand I don't know 1) how similar it remains to GCC internally, or 2) the version of GCC from which it derived -- but it's been around long enough that I'd guess it was GCC 3.x at the most recent, and quite possibly GCC 2.x.
I believe PathScale has created at least one compiler derived from Open64, but they may have others as well.
As far as I know, IBM's compiler is entirely their own creation. I'd guess IBM's (now discontinued) VisualAge for C++ shared some heritage/development/code with XL C++, but don't know that for sure, and can't even begin to guess at the extent of it, even assuming it's true.
|
2,618,516 | 2,618,547 | C++ Report alternatives? | I came across this recommendation for reading the C++ report magazine. However, when I searched for it, i realized it has become defunct.
Can someone please recommend me some other magazine / rss etc which is of the same genre ? I look forward to read more about some of the elusive and other C++ techniques that veterans are using in the field.
I came across Dr. Dobb's journal -> C++ feeds and I think they're pretty good too. Subscribed++
Thanks!
| The obvious choices would be C Vu and Overload, both published by the ACCU (formerly known as the Association of C and C++ Users).
Also, even though this isn't a magazine, a great source of C++related material that is updated quite often is Herb Sutter's blog: Sutter's Mill.
|
2,618,526 | 2,618,534 | Problems Expanding an Array in C++ | I'm writing a simulation for class, and part of it involves the reproduction of organisms. My organisms are kept in an array, and I need to increase the size of the array when they reproduce. Because I have multiple classes for multiple organisms, I used a template:
template <class orgType>
void expandarray(orgType* oldarray, int& numitems, int reproductioncount)
{
orgType *newarray = new orgType[numitems+reproductioncount];
for (int i=0; i<numitems; i++) {
newarray[i] = oldarray[i];
}
numitems += reproductioncount;
delete[] oldarray;
oldarray = newarray;
newarray = NULL;
}
However, this template seems to be somehow corrupting my data. I can run the program fine without reproduction (commenting out the calls to expandarray), but calling this function causes my program to crash. The program does not crash DURING the expandarray function, but crashes on access violation later on.
I've written functions to expand an array hundreds of times, and I have no idea what I screwed up this time. Is there something blatantly wrong in my function? Does it look right to you?
EDIT: Thanks for everyone's help. I can't believe I missed something so obvious. In response to using std::vector: we haven't discussed it in class yet, and as silly as it seems, I need to write code using the methods we've been taught.
| You need to pass oldarray as a reference: orgType *& oldarray. The way it's currently written, the function will delete the caller's array but will not give it the newly allocated one, causing the crash.
Better yet, use std::vector instead of reimplementing it.
|
2,618,625 | 2,618,696 | error: expected constructor, destructor, or type conversion before '(' token | include/TestBullet.h:12: error: expected constructor, destructor, or type conver
sion before '(' token
I hate C++ error messages... lol ^^
Basically, I'm following what was written in this post to try to create a factory class for bullets so they can be instantiated from a string, which will be parsed from an xml file, because I don't want to have a function with a switch for all of the classes because that looks ugly.
Here is my TestBullet.h:
#pragma once
#include "Bullet.h"
#include "BulletFactory.h"
class TestBullet : public Bullet {
public:
void init(BulletData& bulletData);
void update();
};
REGISTER_BULLET(TestBullet); <-- line 12
And my BulletFactory.h:
#pragma once
#include <string>
#include <map>
#include "Bullet.h"
#define REGISTER_BULLET(NAME) BulletFactory::reg<NAME>(#NAME)
#define REGISTER_BULLET_ALT(NAME, CLASS) BulletFactory::reg<CLASS>(NAME)
template<typename T> Bullet * create() { return new T; }
struct BulletFactory {
typedef std::map<std::string, Bullet*(*)()> bulletMapType;
static bulletMapType map;
static Bullet * createInstance(char* s) {
std::string str(s);
bulletMapType::iterator it = map.find(str);
if(it == map.end())
return 0;
return it->second();
}
template<typename T>
static void reg(std::string& s) {
map.insert(std::make_pair(s, &create<T>));
}
};
Thanks in advance.
And unrelated to the error, but is there a way to let Bullet include BulletFactory without creating tons of errors (because of circular inclusion)? This way I would be able to remove #include "BulletFactory.h" from the top of all of the bullet subclasses.
| Here's how you get what you want. (Not using your code, exactly, skips including headers, etc. Just for the idea.):
// bullet_registry.hpp
class bullet;
struct bullet_registry
{
typedef bullet* (*bullet_factory)(void);
std::map<std::string, bullet_factory> mFactories;
};
bullet_registry& get_global_registry(void);
template <typename T>
struct register_bullet
{
register_bullet(const std::string& pName)
{
get_global_registry().mFactories.insert(std::make_pair(pName, create));
}
static bullet* create(void)
{
return new T();
}
};
#define REGISTER_BULLET(x) \
namespace \
{ \
register_bullet _bullet_register_##x(#x); \
}
// bullet_registry.cpp
bullet_registry& get_global_registry(void)
{
// as long as this function is used to get
// a global instance of the registry, it's
// safe to use during static initialization
static bullet_registry result;
return result; // simple global variable with lazy initialization
}
// bullet.hpp
struct my_bullet : bullet { };
// bullet.cpp
REGISTER_BULLET(my_bullet)
This works by making a global variable, which will be initialized at some point during static initialization. When that happens, in its constructor it accesses the global registry and registers it with the name, and the function used to create bullets.
Since static initialization order is unspecified, we put the global manager in a function, so when that function is called the first time the manager is created on-demand and used. This prevents us from using an uninitialized manager, which could be the case if it were a simple global object.
Free free to ask for clarifications.
|
2,618,694 | 2,618,703 | C++ Class Construction and Member Initialization | The first print shows the member value to be false, and the other two prints show it as true. Why does the first output differ from the last two?
#include <vector>
#include <iostream>
using namespace std;
class MyClass
{
public:
bool value;
bool stuff;
};
class Container
{
public:
vector<MyClass> my_classes;
Container()
{
MyClass c;
cout << c.value << endl;
my_classes.push_back(c);
}
};
int main (int argc , char* argv[] )
{
MyClass mc;
cout << mc.value << endl;
Container con;
cout << con.my_classes[0].value << endl;
return 0;
}
| The two members are primitive (non-class) objects and thus uninitialized. That means that their values will be arbitrary at runtime. You must initialize them in the constructor:
class MyClass {
public:
bool value;
bool stuff;
MyClass(): value(false), stuff(false) { }
};
|
2,618,753 | 2,618,805 | C++ domain specific embedded language operators | In numerical oriented languages (Matlab, Fortran) range operator and semantics is very handy when working with multidimensional data.
For example:
A(i:j,k,:n) // represents two-dimensional slice B(i:j,0:n) of A at index k
unfortunately C++ does not have range operator (:). of course it can be emulated using range/slice functor, but semantics is less clean than Matlab. I am prototyping matrix/tensor domain language in C++ and am wondering if there any options to reproduce range operator.
I still would like to rely on C++/prprocessor framework exclusively.
So far I have looked through boost wave which might be an suitable option.
is there any other means to introduce new non-native operators to C++ DSL?
I know you cannot add new operators.am specifically looking for workaround.
One thing I came up (very ugly hack and I do not intend to use):
#define A(r) A[range(((1)?r), ((0)?r))] // assume A overloads []
A(i:j); // abuse ternary operator
| A solution that I've used before is to write an external preprocessor that parses the source and replaces any uses of your custom operator with vanilla C++. For your purposes, a : b uses would be replaced with something like a.operator_range_(b), and operator:() declarations with declarations of range_ operator_range_(). In your makefile you then add a rule that preprocesses source files before compiling them. This can be done with relative ease in Perl.
However, having worked with a similar solution in the past, I do not recommend it. It has the potential to create maintainability and portability issues if you do not remain vigilant of how source is processed and generated.
|
2,619,227 | 2,619,255 | Best way to get ints from a string with whitespace? | I know this is simple, I just can't recall the best way to do this.
I have an input like " 5 15 " that defines the x and y of a 2D vector array.
I simply need those two numbers into int col and int row.
What's the best way to do this? I was attemping stringstreams, but can't figure out the correct code.
Thanks for any help!
| You can do it using a stringstream:
std::string s = " 5 15 ";
std::stringstream ss(s);
int row, column;
ss >> row >> column;
if (!ss)
{
// Do error handling because the extraction failed
}
|
2,619,480 | 2,619,500 | Access Violation When Writing Dynamic 2D Array... Sometimes | This program is meant to generate a dynamic array, however it gives an access violation error when writing when given certain dimensions. Eg: R = 6, C = 5 crashes, but then R = 5, C = 6 doesn't. In case your wondering, it isn't my homework to "fix" this broken program, this is the method we were taught in class. Also part of my assessment is to use this method, so vectors are out. Thanks in advance!
#include <iostream>
using namespace std;
int main(){
const int R = 6;
const int C = 5;
char **d;
d = new char *[R];
for(int i=0; i<C; ++i){
d[i] = new char[C];
}
//initialise
for(int i=0; i<R; ++i){
for(int j=0; j<C; ++j){
d[i][j] = 'd';
cout<<d[i][j];
}
cout<<endl;
}
cout<<endl;
system("pause");
return 0;
}
| for(int i=0; i<C; ++i){
d[i] = new char[C];
}
should be
for(int i=0; i<R; ++i){
d[i] = new char[C];
}
|
2,619,551 | 2,623,662 | Output iterator's value_type | The STL commonly defines an output iterator like so:
template<class Cont>
class insert_iterator
: public iterator<output_iterator_tag,void,void,void,void> {
// ...
Why do output iterators define value_type as void? It would be useful for an algorithm to know what type of value it is supposed to output.
For example, a function that translates a URL query "key1=value1&key2=value2&key3=value3" into any container that holds key-value strings elements.
template<typename Ch,typename Tr,typename Out>
void parse(const std::basic_string<Ch,Tr>& str, Out result)
{
std::basic_string<Ch,Tr> key, value;
// loop over str, parse into p ...
*result = typename iterator_traits<Out>::value_type(key, value);
}
The SGI reference page of value_type hints this is because it's not possible to dereference an output iterator. But that's not the only use of value_type: I might want to instantiate one in order to assign it to the iterator.
What alternative approach is there for constructing a value to output with the output iterator? Two approaches I considered:
Accept a functor parameter that would return an object of the correct type. I still want to have a version of the algorithm that doesn't take that function object parameter though.
Require that the output container holds pair<string,string>, or else a type convertible from that. I wonder if I can do without this requirement, perhaps allow any element that can construct from two std::string s.
| The real value type of the iterator could well be the iterator itself. operator* may easily just return a reference to *this because the real work is done by the assignment operator. You may well find that *it = x; and it = x; have exactly the same effect with output iterators (I suppose special measures might be taken to prevent the latter from compiling).
As such, defining the real value type would be just as useless. Defining it as a void, on the other hand, can prevent errors like:
typename Iter::value_type v = *it; //useless with an output iterator if it compiled
I suppose this is just the limit of the concept of output iterators: they are objects which "abuse" operator overloading, so as to appear pointerlike, whereas in reality something completely different is going on.
Your problem is interesting, though. If you want to support any container, then the output iterators in question would probably be std::insert_iterator, std::front_insert_iterator and std::back_insert_iterator. In this case you could do something like the following:
#include <iterator>
#include <vector>
#include <string>
#include <map>
#include <iostream>
//Iterator has value_type, use it
template <class T, class IterValue>
struct value_type
{
typedef IterValue type;
};
//output iterator, use the container's value_type
template <class Container>
struct value_type<Container, void>
{
typedef typename Container::value_type type;
};
template <class T, class Out>
void parse_aux(Out out)
{
*out = typename value_type<T, typename Out::value_type>::type("a", "b");
}
template <template <class> class Out, class T>
void parse(Out<T> out)
{
parse_aux<T>(out);
}
//variadic template in C++0x could take care of this and other overloads that might be needed
template <template <class, class> class Out, class T, class U>
void parse(Out<T, U> out)
{
parse_aux<T>(out);
}
int main()
{
std::vector<std::pair<std::string, std::string> > vec;
parse(std::back_inserter(vec));
std::cout << vec[0].first << ' ' << vec[0].second << '\n';
std::map<std::string, std::string> map;
parse(std::inserter(map, map.end()));
std::cout << map["a"] << '\n';
//just might also support normal iterators
std::vector<std::pair<std::string, std::string> > vec2(1);
parse(vec2.begin());
std::cout << vec2[0].first << ' ' << vec2[0].second << '\n';
}
It would still only get you this far. I suppose one could take this further, so it can also manage, say, a std::ostream_iterator<printable_type>, but at some point it would get so complex that it takes a god to decipher the error messages, should something go wrong.
|
2,619,630 | 2,619,741 | C++ exceptions binary compatibility | my project uses 2 different C++ compilers, g++ and nvcc (cuda compiler).
I have noticed exception thrown from nvcc object files are not caught in g++ object files.
are C++ exceptions supposed to be binary compatible in the same machine?
what can cause such behavior?
try { kernel_= new cuda:: Kernel(); }
catch (...) { kernel_= NULL; }
// nvcc object
cuda:: Kernel:: Kernel () {
...
if (! impl_) throw;
}
everything else seems to work (C++ objects, operators). To be honest I do not know exceptions very well so maybe there is mistake in the code above.
| nvcc is a wrapper around a normal c++ compiler, and is basically a preprocessor to convert the cuda syntax into something compilable. You can see what compiler it uses with the --verbose flag.
For instance on my machine compiling
// test.cpp
int main(){return 0;}
with nvcc -v gives
#$ _SPACE_=
#$ _MODE_=DEVICE
#$ _HERE_=/usr/local/cuda/bin
#$ _THERE_=/usr/local/cuda/bin
#$ TOP=/usr/local/cuda/bin/..
#$ PATH=/usr/local/cuda/bin/../open64/bin:/usr/local/cuda/bin/../bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/Users/me/bin:/usr/local/aspell/bin:/usr/local/noweb:/usr/local/icon/bin:/usr/local/dmd/bin:/usr/local/cuda/bin:/usr/local/sed/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
#$ INCLUDES="-I/usr/local/cuda/bin/../include"
#$ LIBRARIES= "-L/usr/local/cuda/bin/../lib" -lcudart
#$ CUDAFE_FLAGS=
#$ OPENCC_FLAGS=
#$ PTXAS_FLAGS=
#$ gcc -c -x c++ "-I/usr/local/cuda/bin/../include" -I. -m32 -malign-double -o "/tmp/tmpxft_000010af_00000000-1_test.o" "test.cpp"
#$ g++ -m32 -malign-double -o "a.out" "/tmp/tmpxft_000010af_00000000-1_test.o" "-L/usr/local/cuda/bin/../lib" -lcudart
Using the same compiler/flags as listed here should give you binary compatibility
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.