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,786,946 | 2,786,963 | C++ invoke explicit template constructor | Can you tell me how to invoke template constructor explicitly (in initializer list)?
for example:
struct T {
template<class> T();
};
struct U {
U() : t<void>() {} //does not work
T t;
};
thanks
| It's not possible. The Standard also has a note on this at 14.8.1/7
[Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates. ]
Explanation: This says: Template arguments are passed in angle brackets after a function template name, such as std::make_pair<int, bool>. And constructors don't have a name of their own, but they abuse their class names in various contexts (so U<int>() means: Pass <int> to the class template U, and construct an object by calling the default constructor without arguments). Therefore, one cannot pass template arguments to constructors.
In your case, you are trying to pass template arguments in a member initializer. In that case, there's even more of a problem: It will attempt to parse and interpret t<void> as a base-class type and thinks you want to call the default constructor of a base class. This will fail, of course.
If you can live with it, you can work it around
struct T {
template<class U> T(identity<U>);
};
struct U {
U() : t(identity<void>()) {}
T t;
};
Given identity like it's defined in boost
template<typename T> struct identity { typedef T type; };
Within C++20 you can use std::type_identity as identity type.
https://en.cppreference.com/w/cpp/types/type_identity
|
2,786,995 | 2,787,059 | Is it compulsory to learn about Data Structures if you want to be a Java/C++ programmer? | So do I really need to learn about them ? Isn't there an interesting way to learn about stacks, linked lists, heaps, etc ? I found it a boring subject.
**While posting this question it showed some warning. Am I not allowed to post such a question ? Admins please clarify and I will delete it :/
Warning :: The question you're asking appears subjective and is likely to be closed.
okay..I get it
So what is THE best way to learn them ? What book do I refer ? What website ?
| It's compulsory to learn about data structures if you want to be a programmer. Data structures are your bread-and-butter - if you don't understand things like the behavior, uses, and run-time complexity ('big-O') of at least the basic structures (arrays, linked lists, stacks, queues, trees (binary / n-ary, self-balancing varietes), hash-tables, heaps, graphs) and the algorithms that run on them (insert / locate / delete), you won't know which is appropriate to use under what circumstances.
Every trade has its tools; these are ours. Data structures are the most basic underpinnings of almost any algorithm that you're going to learn. Unless you want to be a cargo cult programmer, you need to understand how they work.
Whether or not there are interesting ways to learn about them is a separate question entirely... :)
|
2,787,002 | 2,787,164 | Is there kind of runtime C++ assembler library around? | For my small hobby project I need to emit machine code from C++ program in runtime. I have base address 0xDEADBEEF and want to write something like this:
Assembler a((void*)0xDEADBEEF);
a.Emit() <<
Push(Reg::Eax) <<
Push(Reg::Ebx) <<
Jmp(0xFEFEFEFE);
Inline assembler isn't my choice because generated machine code is dependent of the program state.
Does anybody know any existing library for doing this? If no, would it be a good idea to develop one from scratch and make it open source? (I mean, will anybody ever use this library if it existed?)
| You could use Nicolas Capen's softwire. Its really not supported any more as he now works on a similar product at Transgaming called SoftAsm. Still it kinda does what you want.
Edit June 2014: - It appears the sourceforge link above has been removed but it appears to be available under an LGPL license here.
|
2,787,156 | 2,787,292 | std::map operator[] and automatically created new objects | I'm a little bit scared about something like this:
std::map<DWORD, DWORD> tmap;
tmap[0]+=1;
tmap[0]+=1;
tmap[0]+=1;
Since DWORD's are not automatically initialized, I'm always afraid of tmap[0] being a random number that is incremented. How does the map know hot to initialize a DWORD if the runtime does not know how to do it?
Is it guaranteed, that the result is always tmap[0] == 3?
| The new object, when inserted into the map by [] operator, is value-initialized. It is ensured by the map implementation, i.e. it is done "automatically" in that sense. For objects of type DWORD (assuming it is a scalar type), value-initialization means zero-initialization.
By definition given in 23.3.1.2, operator [] is a shorthand for
(*((insert(make_pair(x, T()))).first)).second
The T() bit is the new object, which will turn into DWORD() in your case. DWORD() is guaranteed to be zero.
|
2,787,188 | 2,787,646 | CListView Control has limited length for column text | When I set the column text for CListView more than 271 characters, the rest of my buffer is not present.
I set it through LV_COLUMN structure.
Is this a known issue for MFC 4.21?
| Here's yet another answer you won't like. It has nothing to do with your ancient version of MFC, it is a documented limitation for the list view control. From the SDK docs for the LVITEM structure's pszText member:
If the structure receives item
attributes, pszText is a pointer to a
buffer that receives the item text.
Note that although the list-view control allows any length string to be
stored as item text, only the first
260 TCHARs are displayed.
|
2,787,511 | 2,789,517 | boost::bind and << operator in C++ | I would like to bind the << stream operator:
for_each(begin, end, boost::bind(&operator<<, stream, _1));
Unfortunately it does not work:
Error 1 error C2780: 'boost::_bi::bind_t<_bi::dm_result<MT::* ,A1>::type,boost::_mfi::dm<M,T>,_bi::list_av_1<A1>::type> boost::bind(M T::* ,A1)' : expects 2 arguments - 3 provided c:\source\repository\repository\positions.cpp 90
What am I doing wrong ?
| Instead you might try boost.lambda:
//using namespace boost::lambda;
for_each(begin, end, stream << _1));
The reason of your problem is most probably: how on earth can you expect the compiler / bind to know what you are taking the address of if you say &operator<<? (I get a different error simply saying that this is not declared.)
If you really want to do it with bind, you'd have to tell it which operator<< you want to use, e.g assuming int (you'll also need to know, it the operator is overloaded as a member or free function):
bind(static_cast<std::ostream& (std::ostream::*)(int)>(&std::ostream::operator<<), ref(std::cout), _1)
|
2,787,569 | 2,787,594 | copy constructor with default arguments | As far as I know, the copy constructor must be of the form T(const T&) or T(T&). What if I wanted to add default arguments to the signature?
T(const T&, double f = 1.0);
Would that be standards compliant?
| Yes.
§[class.copy]/2:
A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments [ Example: X::X(const X&) and X::X(X&,int=1) are copy constructors.
|
2,787,638 | 2,788,531 | Problem with inner classes of the same name in Visual C++ | I have a problem with Visual C++ 2005, where apparently inner classes with the same name but in different outer classes are confused.
The problem occurs for two layers, where each layer has a listener interface as an inner class. B is a listener of A, and has its own listener in a third layer above it (not shown).
The structure of the code looks like this:
A.h
class A
{
public:
class Listener
{
public:
Listener();
virtual ~Listener() = 0;
};
// ...
};
B.h
class B : public A::Listener
{
class Listener
{
public:
Listener();
virtual ~Listener() = 0;
};
// ...
};
A::Listener() and A::~Listener() are defined in A.cpp.
B.cpp
B::Listener::Listener() {}
B::Listener::~Listener() {}
I get the error
B.cpp(49) : error C2509: '{ctor}' : member function not declared in 'B'
The C++ compiler for Renesas sh2a has no problem with this, but then it is more liberal than Visual C++ in some other respects, too.
If I rename the listener interfaces to have different names the problem goes away, but I'd like to avoid that (the real class names instead of A or B are rather long).
Is what I'm doing correct C++, or is the complaint by Visual C++ justified?
Is there a way to work around this problem without renaming the listener interfaces?
| the code you posted produced the same compiler error you described on my machine. I'm not so sure myself what the problem exactly is, but I have a feeling that inherting from a pure virtual class and declaring a pure virtual class within the descendant might not be a good idea.
I managed to compile a modified version, maybe this helps you solve your problems:
class OuterA
{
public:
class Listener
{
public:
Listener() {}
virtual ~Listener() = 0 {}
};
OuterA() {}
~OuterA(){}
};
class OuterB : public OuterA::Listener
{
public:
class Listener
{
public:
Listener() {}
~Listener() {}
};
OuterB() {}
~OuterB() {}
};
// EDIT to avoid inline ctor and dtor
If you use typedefs to hide the names of the Listeners at least my demo code compiles and links:
// header
class OuterA
{
public:
class Listener
{
public:
Listener();
virtual ~Listener() = 0;
};
OuterA();
~OuterA();
};
class OuterB : public OuterA::Listener
{
public:
class Listener
{
public:
Listener();
virtual ~Listener() = 0;
};
OuterB();
~OuterB();
};
// implementation
OuterA::OuterA(){}
OuterA::~OuterA(){}
OuterA::Listener::Listener(){}
OuterA::Listener::~Listener(){}
typedef OuterB::Listener BListener;
OuterB::OuterB() {}
OuterB::~OuterB(){}
BListener::Listener(){}
BListener::~Listener(){}
|
2,787,717 | 2,787,743 | Copy Constructor in C++ | I have this code
#include <iostream>
using namespace std;
class Test{
public:
int a;
Test(int i=0):a(i){}
~Test(){
cout << a << endl;
}
Test(const Test &){
cout << "copy" << endl;
}
void operator=(const Test &){
cout << "=" << endl;
}
Test operator+(Test& p){
Test res(a+p.a);
return res;
}
};
int main (int argc, char const *argv[]){
Test t1(10), t2(20);
Test t3=t1+t2;
return 0;
}
Output:
30
20
10
Why isn't the copy constructor called here?
| This is a special case called Return Value Optimization in which the compiler is allowed to optimize away temporaries.
|
2,787,756 | 2,787,772 | Call virtual method from base class on object of derived type | class Base
{
public:
virtual void foo() const
{
std::cout << "Base";
}
};
class Derived : public Base
{
public:
virtual void foo() const
{
std::cout << "Derived";
}
};
Derived d; // call Base::foo on this object
Tried casting and function pointers but I couldn't do it. Is it possible to defeat virtual mechanism (only wondering if it's possible)?
| To explicitly call the function foo() defined in Base, use:
d.Base::foo();
|
2,788,040 | 2,788,066 | using win32 api in linux? | I have heard of WINE but I don't like it because it's slow on the computers I have tested and almost always crashes. It also has some unpleasant looking gui.
I am wondering if there is a "win32" library in c/c++ for linux that produces native linux code
so that if I have my source code for windows, I can just recompile and produce a working linux application. Is this possible?
| You're looking for Winelib.
|
2,788,134 | 2,788,168 | Should I Put Critical Section While Getting Connection from OCCI Environment | I'm writing a multi-threaded application. My worker threads get connection from an environment object as follows:.
//EnterCriticalSection(&cs);
conn = env->createConnection(username, password, connStr);
//LeaveCriticalSection(&cs);
For concurrency, should the connection be created in a critical section or not? Does the env need it? And why?
Thanks.
| If createConnection is thread-safe then you don't need it.
If createConnection isn't thread-safe then you do need the critical section.
Consult your documentation to see whether it's thread-safe or not. If it doesn't explicitly say it's thread-safe, them play it safe and wrap it in a critical section.
Edit: Of course, all of the above assumes that multiple threads will be calling createConnection. If they're not, then obviously you won't need the critical section at all.
|
2,788,185 | 2,788,267 | POST request with QWebView | How can I issue a POST request over a QWebView instance?
| I think the information below will help you:
1). Standard Qt example project, called "previewer", which comes with Qt SDK, may help you. For me, the absolute path is:
C:\Qt\4.6.2\examples\webkit\previewer
QWebView class, as I could test it, supports "post method", i.e. you can free open URL with POST page, and tap on the "Open file" button and after that upload any data.
2). About a month ago a have some kind of a problem with posting data (any files) to server, and here was my question.
|
2,788,194 | 2,791,197 | Count Similar iTems in Array | I need to count the similar elements in an array. For example, if i have an array,
array[0,0,0,1,2,3,3].The number of 0's are 3 , no. of 1's are 1 , no. of 2's are 1 , no. of 3's are 2 in this array . I am sorry if this message has been posted before. Help is appreciated. Thanks in advance.
Regards,
THM
P.S : Language is C/C++
| I can think of a few options:
Copy the array into a std::multiset<> and then use the count() or equal_range() member functions to return the counts
Create a std::map<T,unsigned>. The map key (of your array entry type T, which will be an integral type from your example) is the array entry, the value is the count. Increment the count associated with a value every time you encounter an element with that value as you iterate through the array
If the array is sorted use std::equal_range() to find consecutive equal elements, and count them.
There are of course many more, including just iterating though and counting directly.
|
2,788,352 | 2,788,381 | Problems with first argument being string when overloading the + operator in C++ | I have an selfmade Stringclass:
//String.h
String & operator = (const String &);
String & operator = (char*);
const String operator+ (String& s);
const String operator+ (char* sA);
.
.
//in main:
String s1("hi");
String s2("hello");
str2 = str1 + "ok";//this is ok to do
str2 = "ok" + str1;//but not this way
//Shouldn't it automatically detect that one argument is a string and in both cases?
| The + operator should not be a member function, but a free function, so that conversions can be performed on either of its operands. The easiest way to do this is to write operator += as a member and then use it to implement the free function for operator +. Something like:
String operator +( const String & s1, const String & s2 ) {
String result( s1 );
return result += s2;
}
As others have suggested, you can overload for const char * for possible efficiency reasons, but the single function above is all you actually need.
Please note that your code as it stands should give an error for:
String s1("hi");
String s2("hello");
str2 = str1 + "ok"; // not OK!!!
something like:
warning: deprecated conversion from string constant to 'char*'
as the string literal (constant) "ok" is a const char *, not a char *. If your compiler does not give this warning, you should seriously think about upgrading it.
|
2,788,388 | 2,788,535 | When is #include <new> library required in C++? | According to this reference for operator new:
Global dynamic storage operator
functions are special in the standard
library:
All three versions of operator new are declared in the global namespace,
not in the std namespace.
The first and second versions are implicitly declared in every
translation unit of a C++ program: The
header does not need to be
included for them to be present.
This seems to me to imply that the third version of operator new (placement new) is not implicitly declared in every translation unit of a C++ program and the header <new> does need to be included for it to be present. Is that correct?
If so, how is it that using both g++ and MS VC++ Express compilers it seems I can compile code using the third version of new without #include <new> in my source code?
Also, the MSDN Standard C++ Library reference entry on operator new gives some example code for the three forms of operator new which contains the #include <new> statement, however the example seems to compile and run just the same for me without this include?
// new_op_new.cpp
// compile with: /EHsc
#include<new>
#include<iostream>
using namespace std;
class MyClass
{
public:
MyClass( )
{
cout << "Construction MyClass." << this << endl;
};
~MyClass( )
{
imember = 0; cout << "Destructing MyClass." << this << endl;
};
int imember;
};
int main( )
{
// The first form of new delete
MyClass* fPtr = new MyClass;
delete fPtr;
// The second form of new delete
char x[sizeof( MyClass )];
MyClass* fPtr2 = new( &x[0] ) MyClass;
fPtr2 -> ~MyClass();
cout << "The address of x[0] is : " << ( void* )&x[0] << endl;
// The third form of new delete
MyClass* fPtr3 = new( nothrow ) MyClass;
delete fPtr3;
}
Could anyone shed some light on this, and when and why you might need to #include <new> - maybe some example code that will not compile without #include <new>?
| Nothing in C++ prevents standard headers from including other standard headers. So if you include any standard header you might conceivably indirectly include all of them. However, this behaviour is totally implementation dependent, and if you need the features of a specific header you should always explicitly include it yourself.
|
2,788,518 | 5,005,699 | Calling activateWindow on QDialog sends window to background | I am debugging certain application written with C++/Qt4. On Linux it has problems that with certain window managers (gnome-wm/metacity), the main window (based on QDialog) is created in the background (it's not raised). I managed to re-create the scenario using PyQt4 and following code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class PinDialog(QDialog):
def showEvent(self, event):
QDialog.showEvent(self, event)
self.raise_()
self.activateWindow()
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = PinDialog()
app.setActiveWindow(widget)
widget.exec_()
sys.exit(0)
If I remove
self.activateWindow()
the application works as expected. This seems wrong, since documentation for activateWindow
does not specify any conditions under which something like this could happen.
My question is:
Is there any reason to have activateWindow in showEvent in the first place? If there is some reason, what would be good workaround for focusing issues?
| The problem was most probably caused by a bug in Qt. I can't reproduce the same behaviour in recent Qt versions. Originally reproduced on Fedora 13, Fedora 14 works OK.
|
2,788,765 | 2,789,206 | std::make_shared as a default argument does not compile | In Visual C++ (2008 and 2010), the following code does not compile with the following error:
#include <memory>
void Foo( std::shared_ptr< int > test = ::std::make_shared< int >( 5 ) )
{
}
class P
{
void
Foo( std::shared_ptr< int > test = ::std::make_shared< int >( 5 ) )
{
}
};
error C2039: 'make_shared' : is not a member of '`global namespace''
error C3861: 'make_shared': identifier not found
It is complaining about the definition of P::Foo() not ::Foo().
Does anybody know why it is valid for Foo() to have a default argument with std::make_shared but not P::Foo()?
| It looks like a bug in the compiler. Here is the minimal code required to reproduce the problem:
namespace ns
{
template <typename T>
class test
{
};
template <typename T>
test<T> func()
{
return test<T>();
}
}
// Works:
void f(ns::test<int> = ns::func<int>()) { }
class test2
{
// Doesn't work:
void g(ns::test<int> = ns::func<int>())
{
}
};
Visual C++ 2008 and 2010 both report:
error C2783: 'ns::test<T> ns::func(void)' : could not deduce template argument for 'T'
Comeau has no issues with this code.
|
2,788,945 | 2,789,053 | algorithms that destruct and copy_construct | I am currently building my own toy vector for fun, and I was wondering if there is something like the following in the current or next standard or in Boost?
template<class T>
void destruct(T* begin, T* end)
{
while (begin != end)
{
begin -> ~T();
++begin;
}
}
template<class T>
T* copy_construct(T* begin, T* end, T* dst)
{
while (begin != end)
{
new(dst) T(*begin);
++begin;
++dst;
}
return dst;
}
| std::vector, if I'm not mistaken, applies its allocator's construct and destruct functions on individual items, so you could also use binders (like std::tr1::bind) to let std::transform and/or std::for_each do those.
But for the copying loop, there also appears to be std::uninitialized_copy.
|
2,788,958 | 2,789,040 | Drawing and loading a GL_DEPTH_COMPONENT texture | I'm trying to load a depthbuffer from a file and copy it to the depth buffer instead of clearing it every frame.
anyway, i'm a bit new to opengl, so i just tried to load my texture like this:
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, DepthData);
and i try to draw it like this:
glBindTexture(GL_TEXTURE_2D, DepthTexture);
glColorMask(FALSE, FALSE, FALSE, FALSE);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex2f(1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex2f(1.0f, 0.0f);
glEnd();
i tried to load a depthbuffer with every value set to 1.0, and everything i tried to draw got hidden, while it shouldn't.
what should i do?
btw, i do NOT want to use glDrawPixels
| You are indeed drawing a textured quad that is not updating the color buffer and is still updating the depth buffer. However, the values you are writing are the actual depth values of the polygons, and not the values found in the texture! That's why everything ends up being z-culled.
The easiest way to accomplish what you want is to use a custom shader and write a custom gl_FragDepth value reading it from your texture.
|
2,789,017 | 2,789,070 | How to get information about a Windows executable (.exe) using C++ | I have to create a software that will scan several directories and extracts information about the executables found.
I need to do two things:
Determine if a given file is an executable (.exe, .dll, and so on) - Checking the extension is probably not good enough.
Get the information about this executable (the company name, the product name, and so on).
I never did this before and thus am not aware if there is a Windows API (or lightweight C/C++ library) to do that or if it is even possible. I guess it is, because explorer.exe does it.
Do you guys know anything that could point me in the right direction ?
Thank you very much for your help.
| You can verify as much of the PE File Format as you want. If you want to, you can also check for a PE file signature. You can then use the File Version API to retrieve the company name, product name, version numbers, etc.
|
2,789,079 | 2,789,847 | C++ snippet support in visual studio? | I'm writing code in native C++ (not C++/CLR). I know that there is no built-in support for C++ with regards to the snippet manager and snipper picker interfaces, however I found a utility called "snippy" which supposedly can generate C++ snippets. Here is a c++ snippet that the program generated:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>MySnippet</Title>
<Shortcut>MySnippet</Shortcut>
<Description>Just a test snippet</Description>
<Author>Me</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal Editable="true">
<ID>literal1</ID>
<ToolTip>just a placeholder</ToolTip>
<Default>
</Default>
<Function>
</Function>
</Literal>
</Declarations>
<Code Language="cpp"><![CDATA[cout << "$literal1$" << std::endl;]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
If there is support in visual C++, even in a limited capacity, for C++ snippets, how do I add them to my environment, and what are the limitations? All I need is support for basic expansion snippets that I can invoke by typing a shortcut and hitting tab, and which supports basic literals that I can tab through (basically, if it supports the above snippet, I'm good). If this can't be done, are there any free add-ons or extensions to visual studio that support snippets for C++? I'm using both visual studio 2010 and 2008, but I mostly write code in 2010 right now.
| Visual Assist has a snippets feature that is not quite the same as the IDE Snippets feature. It has its pros and cons, but does work in C++.
|
2,789,096 | 2,789,159 | .NET consumer of ActiveX throwing TargetParameterCountException | I have a .NET (3.5 w/ Dev Studio 2008) app that hosts a visual Active X (written in C++ w/ Dev Studio 2003). Have access to all sources, but can't easily move the Active X control up to 2008.
This as worked fine in the past. Made some changes to the Active X control and now, when calling one method on the Active X, I'm getting a TargetParameterCountException 100% of the time. The signature of the Active X method is:
LONG CMyActive::License(LPCTSTR string1, LPCTSTR string2, LONG long1, LPCTSTR string3, LPCTSTR string4);
When viewing the method in object browser of reflector, .NET sees it as:
public virtual int License(string string1, string string2, int long1, string string3, string string4)
I renamed the parameters for demonstration purpose (boss gets twitchy about any code). I left the method name, as it could be relevant.
There are method calls prior that work. I just can't seen to figure out why I'm all of a sudden getting this exception. The HRESULT is 0x8002000e and a quick search seems to indicate that's a general one.
Thanks to all for reading.
Edit
Thanks for the pointers. There is some comfort in knowing others are perplexed. What is odd, is that this did work. This behavior cropped up after a rebuild of the Active X. No interface or other IDL changes. And it's on multiple machines, not just limited to one dev box or such.
Edit 2
For S&G's I added a new method,
LONG CMyActive::XXXLicense(LPCTSTR string1, LPCTSTR string2, LONG long1, LPCTSTR string3, LPCTSTR string4);
Rebuilt everything and now I can call the new method... This smells like a bug either in the compiler and/or the COM interoperability layer of .NET.
| The HRESULT is DISP_E_BADPARAMCOUNT (better for googling than "0x8002000e").
Seems other people have bumped into this problem:
http://www.codeguru.com/forum/showthread.php?t=96353
http://forums.devx.com/showthread.php?t=85215
|
2,789,315 | 2,794,648 | good/full Boot Spirit examples using version 2 syntax | Almost all of the examples I've gone and looked at so far from: http://boost-spirit.com/repository/applications/show_contents.php use the old syntax. I've read and re-read the actual documentation at http://www.boost.org/doc/libs/1_42_0/libs/spirit/doc/html/index.html and the examples therein. I know Joel is starting a compiler series on the blog http://boost-spirit.com/home/ but that hasn't gotten in full swing yet. Any other resources to see worked examples using some more sophisticated/involved aspects in the context of fully working applications?
| Well, there is always the examples directory in Boost SVN: $BOOST_ROOT/libs/spirit/example containing a couple of more sophisticated things to look at. The tests directory adjacent to this contains a huge amount of small tests scrutinizing each and every technique we know of as well.
In addition, Joel and I will have a presentation about the progress we made with the compiler thing you mentioned at BoostCon next week. All of the material will be available right after the talk and all the related code is already in the examples directory in Boost SVN (trunk). We probably will start writing about this effort on the Spirit website after the conference.
I know this is not as much as we have for Spirit.Classic in the application repository, but we really hope to get there over time... Everything depends on what will get contributed by the people using Spirit!
|
2,789,390 | 2,789,413 | How to determine at runtime when your C++ application has the visual studio debugger attached? | How do you determine at runtime whether the visual studio debugger is attached to your process. I've seen instructions for how to do this in .NET, but my process is a native C++ process. Support for detecting Just-in-time debugging would be nice but not a strict requirement.
| The Win32 call IsDebuggerPresent() sounds like it ought to work.
|
2,789,481 | 2,789,509 | Problem calling std::max | I compiled my bison-generated files in Visual Studio and got these errors:
...\position.hh(83): error C2589: '(' : illegal token on right side of '::'
...\position.hh(83): error C2059: syntax error : '::'
...\position.hh(83): error C2589: '(' : illegal token on right side of '::'
...\position.hh(83): error C2059: syntax error : '::'
The corresponding code is:
inline void columns (int count = 1)
{
column = std::max (1u, column + count);
}
I think the problem is with std::max; if I change std::max to equivalent code then there is no problem anymore, but is there a better solution instead of changing the generated code?
Here is the bison file I wrote:
//
// bison.yy
//
%skeleton "lalr1.cc"
%require "2.4.2"
%defines
%define parser_class_name "cmd_parser"
%locations
%debug
%error-verbose
%code requires {
class ParserDriver;
}
%parse-param { ParserDriver& driver }
%lex-param { ParserDriver& driver }
%union {
struct ast *a;
double d;
struct symbol *s;
struct symlist *sl;
int fn;
}
%code {
#include "helper_func.h"
#include "ParserDriver.h"
std::string error_msg = "";
}
%token <d> NUMBER
%token <s> NAME
%token <fn> FUNC
%token EOL
%token IF THEN ELSE WHILE DO LET
%token SYM_TABLE_OVERFLOW
%token UNKNOWN_CHARACTER
%nonassoc <fn> CMP
%right '='
%left '+' '-'
%left '*' '/'
%nonassoc '|' UMINUS
%type <a> exp stmt list explist
%type <sl> symlist
%{
extern int yylex(yy::cmd_parser::semantic_type *yylval,
yy::cmd_parser::location_type* yylloc);
%}
%start calclist
%%
... grammar rules ...
| You are probably including windows.h somewhere, which defines macros named max and min.
You can #define NOMINMAX before including windows.h to prevent it from defining those macros, or you can prevent macro invocation by using an extra set of parentheses:
column = (std::max)(1u, column + count);
|
2,789,545 | 2,789,941 | Texture mapping an NGon? | I'm not sure how to go about figuring out how to map texture coordinates for a 2D NGon (N sided polygon) How can this be done?
The effect I'm trying to achieve is for the texture to fit on the polygon and stretch out accordingly so the whole texture fits on it.
| Remember that when rendering an ngon in OpenGL, it's just a whole bunch of triangles. Also, you're taking some shape and trying to map it to a rectangle, so you have to be extremely critical of how you wish to do this as there many different mappings going from any shape to a rectangular texture.
For example, if I have a 5-gon that is shaped like a square with a point in between two corners, it's easy to map to a texture. What happens when I pull that point out? Do the texture coordinates change when I move vertices around?
One way to do it is to map the circumference of the ngon to the circumference of the rectangle, where the distance traveled from vertex to vertex on the ngon is mapped to a UV coordinate around the circumference of the texture. For example, at 1/4 of the way around it, give it a UV coordinate of (1,0), at half way around the ngon, give the vertex a UV coordinate of (1,1) and 3/4 the way around it, give it a UV of (0,1)--you'll need to interpolate between points, of course, since an ngon won't line up perfectly at every vertex.
|
2,789,735 | 2,789,777 | memset on array of structures in C++ | I have another memset question. It appears as if the code I am editing may have some issues (or it's not done the same way in different files)
A::LRM las[9]; //A and LRM are both structures with BOOLS and INTS
memset(&las, 0, sizeof(las));
typedef Sec SecArray[16];
SecArray rad_array;
memset(rad_array, 0, sizeof(SecArray));
The second example appears to be correct because rad_array is the same as the first position in the array. Then the sizeof(SecArray)) would make sense. The first one doesn't seem correct to me. All structs are just BOOLs and INTS nothing dynamic in them.
My understanding from my other post about memset was that it followed this format.
memset("pointer to object", "what to set it to", "size of object")
Can anyone tell me what exactly is going on here if I am incorrect with my theory.
| Both calls to memset are correct. Both sizeof(las) (or just sizeof las) and sizeof(SecArray) will return the size of the entire array.
If you are worried about the first argument, then again, both will work. The pointer to the entire array (&las) or the pointer to the first element (rad_array in this context) will work equally well with memset.
In general, with regard to sizeof usage, I would recommend using the first approach, since it is type-independent. A good programming practice is to avoid mentioning type names in your statements, i.e. keep type names restricted to declarations as much as possible.
As for the first argument, in case of an array it is a matter of preference, but in general I would say that if you have an object of type T
T t;
and you want to fill it with zeros by using memset, you'd normally do it as
memset(&t, 0, sizeof t);
I don't see why an array should be an exception from that rule (especially if the exact nature of the type is hidden behind a typedef-name). The above memset(&t, ... will work regardless of whether T is an array type, a struct type or any other type. I don't see why one should suddenly drop the & just because T is an array type. Quite the opposite, I'd keep that & to keep the code as type-independent as possible.
Finally, in C++ in both cases the better way to do it would be not to use memset at all and just do
A::LRM las[9] = {};
SecArray rad_array = {};
instead.
|
2,789,852 | 2,789,880 | Passing data structures to different threads | I have an application that will be spawning multiple threads. However, I feel there might be an issue with threads accessing data that they shouldn't be.
Here is the structure of the threaded application (sorry for the crudeness):
MainThread
/ \
/ \
/ \
Thread A Thread B
/ \ / \
/ \ / \
/ \ / \
Thread A_1 Thread A_2 Thread B_1 Thread B_2
Under each lettered thread (which could be many), there will only be two threads and they are fired of sequentially. The issue i'm having is I'm not entirely sure how to pass in a datastructure into these threads.
So, the datastructure is created in MainThread, will be modified in the lettered thread (Thread A, etc) specific to that thread and then a member variable from that datastructure is sent to Letter_Numbered threads.
Currently, the lettered thread class has a member variable and when the class is constructed, the datastructure from mainthread is passed in by reference, invoking the copy constructor so the lettered thread has it's own copy to play with.
The lettered_numbered thread simply takes in a string variable from the data structure within the lettered thread. My question is, is this accceptable? Is there a much better way to ensure each lettered thread gets its own data structure to play with?
Sorry for the somewhat poor explanation, please leave comments and i'll try to clarify.
EDIT:
So my lettered thread constructor should take the VALUE of the data structure, not the reference?
| I would have each thread create it's own copy of the datastructure, e.g. you pass the structure in the constructor and then explicitly create a local copy. Then you are guaranteed that the threads have distinct copies. (You say that it's passsed by reference, and that this invokes the copy constructor. I think you mean pass by value? I feel it's better to explicitly make a copy, to leave no doubt and to make your intent clear. Otherwise someone might later come along and change your pass by value to pass by reference as a "smart optimization".)
EDIT: Removed comment about strings. For some reason, I was assuming .NET.
To ensure strings are privately owned, follow the same procedure, create a copy of the string, which you can then freely modify.
|
2,790,412 | 3,911,532 | 2-byte (UCS-2) wide strings under GCC | when porting my Visual C++ project to GCC, I found out that the wchar_t datatype is 4-byte UTF-32 by default. I could override that with a compiler option, but then the whole wcs* (wcslen, wcscmp, etc.) part of RTL is rendered unusable, since it assumes 4-byte wide strings.
For now, I've reimplemented 5-6 of these functions from scratch and #defined my implementations in. But is there a more elegant option - say, a build of GCC RTL with 2-byte wchar-t quietly sitting somewhere, waiting to be linked?
The specific flavors of GCC I'm after are Xcode on Mac OS X, Cygwin, and the one that comes with Debian Linux Etch.
| Reimplemented 5-6 of more common wcs* functions, #defined my implementations in.
|
2,790,611 | 2,819,123 | Using custom dll in Qt Application | First, my compiler and OS:
Qt Creator 1.3
Qt 4.6 (32 bit)
Windows 7 Ultimate
I want to learn how to create and import a dll in Qt. I've created a *.dll file using Qt Creator, called Shared1.dll which contains nothing but an empty class named Shared1. Now I'd like to use Shared1 class in another Qt project. How can I do that?
Thanks in advance.
| Use your Pro file to include your header files and libraries..
For Header Files:
INCLUDEPATH += "C:\Source\HeaderFiles"
For libraries:
LIBS += "C:\Source\Libraries\MyLib.lib"
Include those header files while using the functions from the libraries.
This works for me... Try it..
|
2,790,632 | 2,790,657 | error of integer overflow | This the part of my OpenGL code, I am getting an error for :
struct Ball {
float x;
float y;
float rot;
float dir;
bool rmv;
Ball* next;
};
Ball* curBall;
void addBall() {
if (balls==NULL) {
balls=new Ball;
balls->next=NULL;
curBall=balls;
} else {
curBall->next=new Ball;
curBall=curBall->next;
curBall->next=NULL;
}
curBall->x=((float)rand()/(float)(RAND_MAX+1))*(ww-1) +1;
curBall->y=((float)rand()/(float)(RAND_MAX+1))*(wh-1) +1;
curBall->dir=((float)rand()/(float)(RAND_MAX+1))*(2*PI-1) +1;
curBall->rot=((float)rand()/(float)(RAND_MAX+1))*(359) +1;
curBall->rmv=false;
}
error :
In function ‘void addBall()’:
file.cpp:120: warning: integer overflow in expression
file.cpp:121: warning: integer overflow in expression
file.cpp:122: warning: integer overflow in expression
file.cpp:123: warning: integer overflow in expression
| Try converting RAND_MAX to a float before adding to it.
curBall->x=((float)rand()/( ((float)RAND_MAX) +1))*(ww-1) +1;
et cetera. RAND_MAX is often equal to INT_MAX, the largest value an integer could hold, thus adding 1 to it while it's still considered an integer pushes it over the integer limit.
|
2,790,969 | 2,791,128 | How to program a connection pool? | Is there a known algorithm for implementing a connection pool? If not what are the known algorithms and what are their trade-offs?
What design patterns are common when designing and programming a connection pool?
Are there any code examples implement a connection pool using boost.asio?
Is it a good idea to use a connection pool for persisting connections (not http)?
How is threading related to connection pooling? When do you need a new thread?
| If you are looking for a pure thread-pooling policy (may be a connection or any resource) there are two simple approaches viz:-
Half Sync/Half Async Model (usually using using message queues to pass information).
Leaders/Followers Model (usually using request queues to pass information).
The first approach goes like this:-
You create a pool of threads to
handle a resource. Often this size
(number of threads) needs to be
configurable. Call these threads
'Workers'.
You then create a master thread that
will dispatch the work to the
Worker threads. The application program dispatches the task as a
message to the master thread.
The master thread puts the same on
the message Q of a chosen Worker
thread and the Worker thread removes itself from the
pool. Choosing and removing the
Worker thread needs synchronization.
After the Worker completes the
task, it returns to the thread-pool.
The master thread itself can consume the tasks it gets in FCFS or a prioritized manner. This will depend on your implementation.
The second model (Leader/Followers) goes something like this:-
Create a thread pool. Initially all
are Workers. Then elect a
Leader, automatically rest-all become followers. Note that electing
a Leader has to be synchronized.
Put all the data to be processed on a
single request Q.
The thread-pool Leader dequeues
the task. It then immediately
elects a new Leader and starts executing the task.
The new Leader picks up the next
task.
There may be other approaches as well, but the ones outlined above are simple that work with most use-cases.
Half Sync/Half Async Major Weakness:-
Higher context switching,
synchronization, and data copying
overhead.
Leader/Follwers Major Weakness:-
Implementation complexity of
Leader election in thread pool.
Now you can decide for yourself the more correct approach.
HTH,
|
2,791,169 | 2,791,353 | Practise Questions for Templates,Functors,CallBack functions in c++? | I have been reading templates,functors,callback function for the past week and have referred some good books and articles.
I however feel that, unless I can get good practice - programming in templates and use functors-callbacks there is no way I can really understand all the concepts or fluently use them while coding.
Could anyone suggest some articles or books or websites where , there is a definition of the problem and also a solution to the same. I could just write code for the problem and check later on if my solution is good enough..
I am also aware that some of our stack-overflow members are experts in templates and callback functions. It would be great if they could design a problem and also post a solution , where a lot of template beginners like me could benefit.
| A good exercise is to replace named functions with anonymous functors. For example, instead of using a predicate such as
bool is_overdrawn(const Account& account)
{
return !account.is_balanced();
}
, you can synthesize a functor via std::not1(std::mem_fun_ref(&Account::is_balanced)).
|
2,791,470 | 2,791,589 | How to get forkpty/execvp() to properly handle redirection and other bash-isms? | I've got a GUI C++ program that takes a shell command from the user, calls forkpty() and execvp() to execute that command in a child process, while the parent (GUI) process reads the child process's stdout/stderr output and displays it in the GUI.
This all works nicely (under Linux and MacOS/X). For example, if the user enters "ls -l /foo", the GUI will display the contents of the /foo folder.
However, bash niceties like output redirection aren't handled. For example, if the user enters "echo bar > /foo/bar.txt", the child process will output the text "bar > /foo/bar.txt", instead of writing the text "bar" to the file "/foo/bar.txt".
Presumably this is because execvp() is running the executable command "echo" directly, instead of running /bin/bash and handing it the user's command to massage/preprocess.
My question is, what is the correct child process invocation to use, in order to make the system behave exactly as if the user had typed in his string at the bash prompt? I tried wrapping the user's command with a /bin/bash invocation, like this: /bin/bash -c the_string_the_user_entered, but that didn't seem to work. Any hints?
ps Just calling system() isn't a good option, since it would cause my GUI to block until the child process exits, and some child processes may not exit for a long time (if ever!)
| If you want the shell to do the I/O redirection, you need to invoke the shell so it does the I/O redirection.
char *args[4];
args[0] = "bash";
args[1] = "-c";
args[2] = ...string containing command line with I/O redirection...;
args[4] = 0;
execv("/bin/bash", args);
Note the change from execvp() to execv(); you know where the shell is - at least, I gave it an absolute path - so the path-search is not relevant any more.
|
2,791,477 | 2,791,607 | Random numbers from binomial distribution | I need to generate quickly lots of random numbers from binomial distributions for dramatically different trial sizes (most, however, will be small). I was hoping not to have to code an algorithm by hand (see, e.g., this related discussion from November), because I'm a novice programmer and don't like reinventing wheels. It appears Boost does not supply a generator for binomially distributed variates, but TR1 and GSL do. Is there a good reason to choose one over the other, or is it better that I write something customized to my situation? I don't know if this makes sense, but I'll alternate between generating numbers from uniform distributions and binomial distributions throughout the program, and I'd like for them to share the same seed and to minimize overhead. I'd love some advice or examples for what I should be considering.
| Boost 1.43 appears to support binomial distributions. You can use boost::variate_generator to connect your source of randomness to the type
of distribution you want to sample from.
So your code might look something like this (Disclaimer: not tested!):
boost::mt19937 rng; // produces randomness out of thin air
// see pseudo-random number generators
const int n = 20;
const double p = 0.5;
boost::binomial<> my_binomial(n,p); // binomial distribution with n=20, p=0.5
// see random number distributions
boost::variate_generator<boost::mt19937&, boost::binomial<> >
next_value(rng, my_binomial); // glues randomness with mapping
int x = next_value(); // simulate flipping a fair coin 20 times
|
2,791,540 | 2,791,550 | C++ Memory allocation question involving vectors | vector< int > vect;
int *int_ptr = new int(10);
vect.push_back( *int_ptr );
I under stand that every "new" needs to be followed by a "delete" at some point but does the clear() method clean this memory?
What about this method of doing the same thing:
vector< int > vect;
int int_var = 10;
vect.push_back( int_var );
From what I understand, clear() calls the variables destructors, but both vect.push_back() methods in this example push an object on the vector, not a pointer. so does the first example using an int pointer need something other than clear() to clean up memory?
| The first method leaks because the vector never takes ownership of the allocated pointer. In fact, it doesn't contain a pointer at all, only a copy of the value.
The second method does not leak, as no memory is dynamically allocated (except internally in the vector -- it will handle that memory itself).
|
2,791,546 | 2,791,560 | How do you delete a pointer without deleting the data the pointer points to? | I have a pointer that points to an array and another pointer referencing the same array. How do i delete any one of those pointers without killing the array such that the second undeleted pointer still works?
for example:
int* pointer1 = new int [1000];
int* pointer2;
pointer2 = pointer1;
Now i want to get rid of pointer1, how would i do it such that i can continue to access the array normaly through pointer2?
| Those pointers are on the stack; you don't have to delete them. Just ignore pointer1 and it will go away at the end of the block.
|
2,791,653 | 2,791,876 | Passing C++ object to C++ code through Python? | I have written some physics simulation code in C++ and parsing the input text files is a bottleneck of it. As one of the input parameters, the user has to specify a math function which will be evaluated many times at run-time. The C++ code has some pre-defined function classes for this (they are actually quite complex on the math side) and some limited parsing capability but I am not satisfied with this construction at all.
What I need is that both the algorithm and the function evaluation remain speedy, so it is advantageous to keep them both as compiled code (and preferrably, the math functions as C++ function objects). However I thought of glueing the whole simulation together with Python: the user could specify the input parameters in a Python script, while also implementing storage, visualization of the results (matplotlib) and GUI, too, in Python.
I know that most of the time, exposing C++ classes can be done, e.g. with SWIG but I still have a question concerning the parsing of the user defined math function in Python:
Is it possible to somehow to construct a C++ function object in Python and pass it to the C++ algorithm?
E.g. when I call
f = WrappedCPPGaussianFunctionClass(sigma=0.5)
WrappedCPPAlgorithm(f)
in Python, it would return a pointer to a C++ object which would then be passed to a C++ routine requiring such a pointer, or something similar... (don't ask me about memory management in this case, though :S)
The point is that no callback should be made to Python code in the algorithm. Later I would like to extend this example to also do some simple expression parsing on the Python side, such as sum or product of functions, and return some compound, parse-tree like C++ object but let's stay at the basics for now.
Sorry for the long post and thx for the suggestions in advance.
| I do things similar to this all the time. The simplest solution, and the one I usually pick because, if nothing else, I'm lazy, is to flatten your API to a C-like API and then just pass pointers to and from Python (or your other language of choice).
First create your classes
class MyFunctionClass
{
public:
MyFunctionClass(int Param)
...
};
class MyAlgorithmClass
{
public:
MyAlgorithmClass(myfunctionclass& Func)
...
};
Then create a C-style api of functions that creates and destroys those classes. I usually flatted in out to pass void* around becuase the languages I use don't keep type safety anyway. It's just easier that way. Just make sure to cast back to the right type before you actually use the void*
void* CreateFunction(int Param)
{
return new MyFunctionClass(Param);
}
void DeleteFunction(void* pFunc)
{
if (pFunc)
delete (MyFunctionClass*)pFunc;
}
void* CreateAlgorithm(void* pFunc)
{
return new MyAlgorithmClass(*(MyFunctionClass*)pFunc)
}
void DelteAlgorithm(void* pAlg)
{
if (pAlg)
delete (MyAlgorithmClass*)pAlg;
}
No all you need to do is make python call those C-style function. In fact, they can (and probably should) be extern "c" functions to make the linking that much easier.
|
2,791,739 | 2,906,921 | C++ packing a typedef enum | typedef enum BeNeLux
{
BELGIUM,
NETHERLANDS,
LUXEMBURG
} _ASSOCIATIONS_ BeNeLux;
When I try to compile this with C++ Compiler, I am getting errors, but it seems to work fine with a C compiler. So here's the question. Is it possible to pack an enum in C++, or can someone see why I would get the error?
The error is:
"semicolon missing after declaration of BeNeLux".
I know, after checking and rechecking, that there definitely is a semicolon there, and in any places required in the rest of the code.
Addendum:
_PACKAGE_ was just an example. I am renaming it.
_ASSOCIATIONS_ is not a type of BeNeLux:
#define _ASSOCIATIONS_ __attribute__((packed))
The code is iffed, but only to make sure it is GNU C/C++.
#if defined (__GNUC__)
#define _ASSOCIATIONS_ __attribute__((packed))
#else
#define _ASSOCIATIONS_
Would this cause problems? I thought (GNUC) worked for both C and C++
Addendum 2:
I even tried
#ifdef __cplusplus
extern "C" {
#endif
typedef enum BeNeLux
{
BELGIUM,
NETHERLANDS,
LUXEMBURG
} _ASSOCIATIONS_ BeNeLux;
#ifdef __cplusplus
}
#endif
No joy. Anyone?
Note: -fshort-enums is not a possibility; looking for a programmatic solution.
| UPDATE:
For C++11 and later, you can specify the underlying type of enums. For example:
enum BeNeLux : uint8_t {
BELGIUM,
NETHERLANDS,
LUXEMBURG
};
But this only applies if the code will be C++ only. If the code needs to be compatible with both C and C++, I believe my original answer still applies.
I don't think that there is something that does exactly what you want here. I assume you are trying to create a type that is the smallest type for the enum's range.
If you need this type of control, I would recommend something like this:
typedef unsigned char BeNeLux;
static const BeNeLux BELGIUM = 0;
static const BeNeLux NETHERLANDS = 1;
static const BeNeLux LUXEMBURG = 2;
not quite as pretty and possibly a little less type safe. But has the effect that you want. sizeof(BeNeLux) == 1 and you have a named constant for all values in the range. A good compiler won't even allocate a variable for static const integer values so long as you never attempt to use the address of it.
|
2,791,852 | 2,791,908 | C++ exam on string class implementation | I just took an exam where I was asked the following:
Write the function body of each of the methods GenStrLen, InsertChar and StrReverse for the given code below. You must take into consideration the following;
How strings are constructed in C++
The string must not overflow
Insertion of character increases its length by 1
An empty string is indicated by StrLen = 0
class Strings {
private:
char str[80];
int StrLen;
public:
// Constructor
Strings() {
StrLen=0;
};
// A function for returning the length of the string 'str'
int GetStrLen(void) {
};
// A function to inser a character 'ch' at the end of the string 'str'
void InsertChar(char ch) {
};
// A function to reverse the content of the string 'str'
void StrReverse(void) {
};
};
The answer I gave was something like this (see bellow). My one of problem is that used many extra variables and that makes me believe am not doing it the best possible way, and the other thing is that is not working....
class Strings {
private:
char str[80];
int StrLen;
int index; // *** Had to add this ***
public:
Strings(){
StrLen=0;
}
int GetStrLen(void){
for (int i=0 ; str[i]!='\0' ; i++)
index++;
return index; // *** Here am getting a weird value, something like 1829584505306 ***
}
void InsertChar(char ch){
str[index] = ch; // *** Not sure if this is correct cuz I was not given int index ***
}
void StrRevrse(void){
GetStrLen();
char revStr[index+1];
for (int i=0 ; str[i]!='\0' ; i++){
for (int r=index ; r>0 ; r--)
revStr[r] = str[i];
}
}
};
I would appreciate if anyone could explain me roughly what is the best way to have answered the question and why. Also how come my professor closes each class function like " }; ", I thought that was only used for ending classes and constructors only.
Thanks a lot for your help.
| First, the trivial }; question is just a matter of style. I do that too when I put function bodies inside class declarations. In that case the ; is just an empty statement and doesn't change the meaning of the program. It can be left out of the end of the functions (but not the end of the class).
Here's some major problems with what you wrote:
You never initialize the contents of str. It's not guaranteed to start out with \0 bytes.
You never initialize index, you only set it within GetStrLen. It could have value -19281281 when the program starts. What if someone calls InsertChar before they call GetStrLen?
You never update index in InsertChar. What if someone calls InsertChar twice in a row?
In StrReverse, you create a reversed string called revStr, but then you never do anything with it. The string in str stays the same afterwords.
The confusing part to me is why you created a new variable called index, presumably to track the index of one-past-the-last character the string, when there was already a variable called StrLen for this purpose, which you totally ignored. The index of of one-past-the-last character is the length of the string, so you should just have kept the length of the string up to date, and used that, e.g.
int GetStrLen(void){
return StrLen;
}
void InsertChar(char ch){
if (StrLen < 80) {
str[StrLen] = ch;
StrLen = StrLen + 1; // Update the length of the string
} else {
// Do not allow the string to overflow. Normally, you would throw an exception here
// but if you don't know what that is, you instructor was probably just expecting
// you to return without trying to insert the character.
throw std::overflow_error();
}
}
Your algorithm for string reversal, however, is just completely wrong. Think through what that code says (assuming index is initialized and updated correctly elsewhere). It says "for every character in str, overwrite the entirety of revStr, backwards, with this character". If str started out as "Hello World", revStr would end up as "ddddddddddd", since d is the last character in str.
What you should do is something like this:
void StrReverse() {
char revStr[80];
for (int i = 0; i < StrLen; ++i) {
revStr[(StrLen - 1) - i] = str[i];
}
}
Take note of how that works. Say that StrLen = 10. Then we're copying position 0 of str into position 9 of revStr, and then position 1 of str into position 9 of revStr, etc, etc, until we copy position StrLen - 1 of str into position 0 of revStr.
But then you've got a reversed string in revStr and you're still missing the part where you put that back into str, so the complete method would look like
void StrReverse() {
char revStr[80];
for (int i = 0; i < StrLen; ++i) {
revStr[(StrLen - 1) - i] = str[i];
}
for (int i = 0; i < StrLen; ++i) {
str[i] = revStr[i];
}
}
And there are cleverer ways to do this where you don't have to have a temporary string revStr, but the above is perfectly functional and would be a correct answer to the problem.
By the way, you really don't need to worry about NULL bytes (\0s) at all in this code. The fact that you are (or at least you should be) tracking the length of the string with the StrLen variable makes the end sentinel unnecessary since using StrLen you already know the point beyond which the contents of str should be ignored.
|
2,791,870 | 2,791,887 | Why can't I access a const vector with iterator? | My example is as below. I found out the problem is with "const" in function void test's parameter. I don't know why the compiler does not allow. Could anybody tell me? Thanks.
vector<int> p;
void test(const vector<int> &blah)
{
vector<int>::iterator it;
for (it=blah.begin(); it!=blah.end(); it++)
{
cout<<*it<<" ";
}
}
int main()
{
p.push_back(1);
p.push_back(2);
p.push_back(3);
test(p);
return 0;
}
| An iterator is defined as returning a reference to the contained object. This would break the const-ness of the vector if it was allowed. Use const_iterator instead.
|
2,792,028 | 2,792,103 | initializer_list not working in VC10 | i wrote this program in VC++ 2010:
class class1
{
public:
class1 (initializer_list<int> a){};
int foo;
float Bar;
};
void main()
{
class1 c = {2,3};
getchar();
}
but i get this errors when i compile project:
Error 1 error C2552: 'c' :
non-aggregates cannot be initialized
with initializer
list c:\users\pswin\documents\visual
studio
2010\projects\test_c++0x\test_c++0x\main.cpp 27
and
2 IntelliSense: initialization with
'{...}' is not allowed for object of
type
"class1" c:\users\pswin\documents\visual
studio
2010\projects\test_c++0x\test_c++0x\main.cpp 27
what is the problem?
| It shouldn't be supported at all:
[...] the C++0x Core Language feature of initializer lists and the associated Standard Library changes weren't implemented in VC10.
The error message refers to the pre-C++0x feature of aggregate initialization, which allows the initialization of certain user-defined types by using curly braces:
struct pair { int first; char second; };
pair p = { 0, 'c' };
Aggregates are defined in §8.5.1:
An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).
When an aggregate is initialized the initializer can contain an initializer-clause consisting of a brace- enclosed, comma-separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order. If the aggregate contains subaggregates, this rule applies recursively to the members of the subaggregate.
|
2,792,238 | 2,803,318 | variable scope when adding a value to a vector in class constructor | I have a level class and a Enemy_control class that is based off an vector that takes in Enemys as values.
in my level constructor I have:
Enemy tmp( 1200 );
enemys.Add_enemy( tmp ); // this adds tmp to the vector in Enemy_control
enemys being a variable of type Enemy_control. My program crashes after these statements complaining about some destructor problem in level and enemy_control and enemy.
Level1::Level1() : Levels()
{
bgX1 = -60; // -60
bgX2 = -130; // -110
bgX3 = -240; // -
bgY=0; // is this used anymore?
// characterY=330;
max_right_movement=500;
max_left_movement=300;
// More test
jump_max = 110;
player_current_y = 340;
jump_spd = 4;
player_current_floor_y = 340;
//CONST_LEVEL1_MAIN_Y = new int( 340 );
scrolling = true;
scrolling_right = true; // this var is in levels
level_alive = true;
restart_level = false;
player_level_x = 300;
player_screen_x = 300;
level_end_point = 1035 * 10;
level_start_point = 0;
// create enemys in the level
Enemy tmp( 1200 );
enemys.Add_enemy( tmp );
// tmp.Set_enemy( 4600 );
// enemys.Add_enemy( tmp );
scoreTitle = new MyText(25);
score = new MyText(25);
high_score=0;
//onblock=0;
load( "grafx/level1/clouds.png", "grafx/level1/mountain.png", "grafx/level1/ground.png", "sounds/level1music.ogg" );
}
and enemy.h:
/* Enemy.h
* obg
* 1-13-10
*/
#ifndef ENEMY_H
#define ENEMY_H
#include "Character.h"
#include <vector>
class Enemy : public Character
{
private:
int enemy_speed,
DRAW_X,
spawn_x,
distance_to_enemy,
frame_left,
frame_right,
death_frame_x,
death_frame_y;
int bullet_fire_rate;
bool following_player;
private:
void Draw_enemy_going_right( SDL_Surface *video_surface );
void Draw_enemy_going_left( SDL_Surface *video_surface );
void Draw_death( int bgX3, int y, SDL_Surface *video_surface );
void Move_frame_left();
void Move_frame_right();
void Draw_me( int bgX3, int y, SDL_Surface *video_surface, int player_level_x, int player_screen_x );
void Fire_bullet();
public:
Enemy( int spawn_x );
~Enemy();
//void Set_enemy( int spawn_x );
void Draw( int bgX3, int y, SDL_Surface *video_surface, int player_level_x, int player_screen_x );
bool Following_player();
};
class Enemy_control
{
private:
vector< Enemy > enemy_vector; // change this to a vector
public:
Enemy_control();
~Enemy_control();
void Add_enemy( Enemy a_enemy );
void Draw( int bgX3, int y, SDL_Surface *video_surface, int player_level_x, int player_screen_x );
//void Free_list_from_memory();
};
Enemy constructor:
Enemy::Enemy( int spawn_x ) : Character()
{
character_image.load( "grafx/enemy1.gif" );
health = 400;
damage = 20;
DRAW_X = spawn_x;
this->spawn_x = spawn_x;
distance_to_enemy = 230;
enemy_speed = 3;
frame_left = 0;
frame_right = 0;
death_frame_x = 390;
death_frame_y = 0;
following_player = false;
bullet_fire_rate = 0;
sprite_info.w = 63;
sprite_info.h = 74;
cout << "enemy built please call Set_enemy()\n";
}
Any ideas?
| As alread pointed out the description of your problem is not really precise. One of the things which strikes me as odd is why the destructor of any of your classes gets called. Looking at your code it becomes clear that Enemy tmp is a local instance which gets cleaned up after leaving the Level constructor. The Add_Enemy() function receives a copy of this local object. Since you provide no copy constructor the call to character_image.load( "grafx/enemy1.gif" ); will not be executed within the copy constructor and therefor the Enemy objects you store will have no image.
Maybe you should consider something like this:
Enemy* tmp = new Enemy( 1200 ); // dynamic allocation of Enemy
enemey.Add_enemy( tmp );
If you do someting like this you need to change your vector to store pointers to Enemy objects
like std::vector< Enemy* > enemies. Do not forget to delete the dynamically allocated objects within the destructor of Enemy_control.
|
2,792,443 | 2,792,459 | Finding the centroid of a polygon? | To get the center, I have tried, for each vertex, to add to the total, divide by the number of vertices.
I've also tried to find the topmost, bottommost -> get midpoint... find leftmost, rightmost, find the midpoint.
Both of these did not return the perfect center because I'm relying on the center to scale a polygon.
I want to scale my polygons, so I may put a border around them.
What is the best way to find the centroid of a polygon given that the polygon may be concave, convex and have many many sides of various lengths?
| The formula is given here for vertices sorted by their occurance along the polygon's perimeter.
For those having difficulty understanding the sigma notation in those formulas, here is some C++ code showing how to do the computation:
#include <iostream>
struct Point2D
{
double x;
double y;
};
Point2D compute2DPolygonCentroid(const Point2D* vertices, int vertexCount)
{
Point2D centroid = {0, 0};
double signedArea = 0.0;
double x0 = 0.0; // Current vertex X
double y0 = 0.0; // Current vertex Y
double x1 = 0.0; // Next vertex X
double y1 = 0.0; // Next vertex Y
double a = 0.0; // Partial signed area
// For all vertices except last
int i=0;
for (i=0; i<vertexCount-1; ++i)
{
x0 = vertices[i].x;
y0 = vertices[i].y;
x1 = vertices[i+1].x;
y1 = vertices[i+1].y;
a = x0*y1 - x1*y0;
signedArea += a;
centroid.x += (x0 + x1)*a;
centroid.y += (y0 + y1)*a;
}
// Do last vertex separately to avoid performing an expensive
// modulus operation in each iteration.
x0 = vertices[i].x;
y0 = vertices[i].y;
x1 = vertices[0].x;
y1 = vertices[0].y;
a = x0*y1 - x1*y0;
signedArea += a;
centroid.x += (x0 + x1)*a;
centroid.y += (y0 + y1)*a;
signedArea *= 0.5;
centroid.x /= (6.0*signedArea);
centroid.y /= (6.0*signedArea);
return centroid;
}
int main()
{
Point2D polygon[] = {{0.0,0.0}, {0.0,10.0}, {10.0,10.0}, {10.0,0.0}};
size_t vertexCount = sizeof(polygon) / sizeof(polygon[0]);
Point2D centroid = compute2DPolygonCentroid(polygon, vertexCount);
std::cout << "Centroid is (" << centroid.x << ", " << centroid.y << ")\n";
}
I've only tested this for a square polygon in the upper-right x/y quadrant.
If you don't mind performing two (potentially expensive) extra modulus operations in each iteration, then you can simplify the previous compute2DPolygonCentroid function to the following:
Point2D compute2DPolygonCentroid(const Point2D* vertices, int vertexCount)
{
Point2D centroid = {0, 0};
double signedArea = 0.0;
double x0 = 0.0; // Current vertex X
double y0 = 0.0; // Current vertex Y
double x1 = 0.0; // Next vertex X
double y1 = 0.0; // Next vertex Y
double a = 0.0; // Partial signed area
// For all vertices
int i=0;
for (i=0; i<vertexCount; ++i)
{
x0 = vertices[i].x;
y0 = vertices[i].y;
x1 = vertices[(i+1) % vertexCount].x;
y1 = vertices[(i+1) % vertexCount].y;
a = x0*y1 - x1*y0;
signedArea += a;
centroid.x += (x0 + x1)*a;
centroid.y += (y0 + y1)*a;
}
signedArea *= 0.5;
centroid.x /= (6.0*signedArea);
centroid.y /= (6.0*signedArea);
return centroid;
}
|
2,792,520 | 2,834,241 | use qt and django to create desktop apps | I had this idea of creating desktop apps using django. The principe being:
- Write the django app, and use something like cherrypy to serve it.
- Write a Qt app in C++ to access it and this by using QtWebview (webkit)
I'd like to "bundle" this in a single app. The lighter, the better :)
So here are my questions and if you have better ideas and suggestions, please
share them :)
Is it possible to serve a django app with a c++ one? (a c++ server embedding python)?
anyone did this before? Do you have some articles, blog posts?
Thanks a lot!
| Look at http://www.python-camelot.com/
It says "A python GUI framework on top of Sqlalchemy and PyQt, inspired by the Django admin interface."
|
2,792,604 | 2,792,666 | Compiling a Windows C++ program in g++ | I'm trying to compile a Windows C++ program in g++. This is what I get.
/usr/include/c++/4.4/backward/backward_warning.h:28:2: warning: #warning This file includes at least one deprecated or antiquated header which may be removed without further notice at a future date. Please use a non-deprecated interface with equivalent functionality instead. For a listing of replacement headers and interfaces, consult the file backward_warning.h. To disable this warning use -Wno-deprecated.
btree.cpp:1204: error: ‘_TCHAR’ has not been declared
btree.cpp: In function ‘int _tmain(int, int**)’:
btree.cpp:1218: error: ‘__int64’ was not declared in this scope
btree.cpp:1218: error: expected ‘;’ before ‘frequency’
btree.cpp:1220: error: ‘LARGE_INTEGER’ was not declared in this scope
btree.cpp:1220: error: expected primary-expression before ‘)’ token
btree.cpp:1220: error: ‘frequency’ was not declared in this scope
btree.cpp:1220: error: ‘QueryPerformanceFrequency’ was not declared in this scope
btree.cpp:1262: error: expected primary-expression before ‘)’ token
btree.cpp:1262: error: ‘start’ was not declared in this scope
btree.cpp:1262: error: ‘QueryPerformanceCounter’ was not declared in this scope
btree.cpp:1264: error: name lookup of ‘i’ changed for ISO ‘for’ scoping
btree.cpp:1264: note: (if you use ‘-fpermissive’ G++ will accept your code)
btree.cpp:1304: error: expected primary-expression before ‘)’ token
btree.cpp:1304: error: ‘end’ was not declared in this scope
btree.cpp:1306: error: ‘total’ was not declared in this scope
btree.cpp:1316: error: ‘getchar’ was not declared in this scope
The first thing I noticed is that there are these variable types called _TCHAR, _int64, and LARGE_INTEGER, which is probably a Windows thing. What can these be changed to so that they will work in g++?
Also, if there's anything else in here that you know can be converted to g++, that would be helpful.
I got the code from here:
http://touc.org/btree.html
| From the linked page:
// the main function is just some code to test the b-tree. it inserts 100,000 elements,
// then searches for each of them, then deletes them in reverse order (also tested in
// forward order) and searches for all 100,000 elements after each deletion to ensure that
// all remaining elements remain accessible.
If you ditch _tmain altogether, you should mostly be good to go. __int64 and LARGE_INTEGER are only being used so that QueryPerformanceCounter can be called, and that's only being called from a test main function. It looks like the code is otherwise relatively portable C++, and indeed it looks like the errors only really start in _tmain anyway.
|
2,792,704 | 2,792,735 | How to use gdb to find a floating point exception in g++ code | I have a g++ program that runs without user input. Somewhere the program is interrupted and it says "Floating point exception." Can gdb help me find what's causing this in my code? How?
| You can get help on GDB here and at Gnu's site here.
But the basics are this:
$ gdb ./your_program // start gdb on the program
> run // run the program
> run argv1 argv2 // or run it with command line arguments
(floating point exception) // let it run until exception occurs
> bt // bt will show the stack trace
Here are some gdb settings on how to make sure it stops on floating point exceptions.
|
2,792,770 | 2,792,786 | Accessing a webpage in C++ | Is there a good, simple library which allows C++ to load a webpage? I just want to grab the source as text. I'm not using any IDE or significant library, just straight command line.
Tangentially, is there something fundamental I'm missing about programming in C++? I would think any language in common use today would have droves of web-based functionality, being so central to computer usage, but I can find next to no discussion on how to accomplish it. I realise C++ significantly predates the modern internet, so it lacking any core ability in the regard is reasonable, but the fact that relevant libraries seem so sparse is baffling.
Thanks for your help.
| Sure, for example libcurl is powerful and popular.
Internet-related libraries for C++ are extremely abundant -- they're just not part of the C++ standard, partly because the current version of that standard is so old, though I'm sure that's not the only reason. But turn to the world of open sources and you'll find more than you can shake a stick at.
|
2,793,425 | 2,793,429 | Seeking to a line in a file in g++ | Is there a way that I can seek to a certain line in a file to read or write data?
Let's say I want to write some data starting on the 10th line in a text file. There might be some data already in the first few lines, or the file could even be empty. Is there a way I can seek directly to the line I want without having to worry about what's already in the file?
| You can seek to a position in a file, but that position must be a character offset from the start, end or current position - see for example fseek(). There is no way of seeking to a particular line, unless all the lines are exactly the same length.
|
2,793,588 | 2,793,614 | two classes contain objects of each other | i hope there's a simple answer to this.
without getting too complicated i have two classes. an "Animal" and a "Cell"
Cell contains an Animal as a member.
Animal has methods that accept Cells in their parameters.
i'm just confused as to how i #include each class the others header?
i've only ever had to go up a chain of classes and just included the last class header in the next and so on, but this circular situation has me a bit lost.
i hope that makes sense, any help greatly appreciated.
| You can use forward declarations to overcome the problem of circular references.
Example:
//animal.h
#include "cell.h"
class Animal {
public:
void foo (Cell cell);
}
// cell.h
class Animal; // forward declaration
class Cell {
private:
Animal * m_animal; // pointer to Animal object
}
|
2,793,694 | 2,793,731 | Dynamic allocating of const member structures | I've got class which is using plain-only-data struct with const variables and I'm not sure, if I'm allocating these structures in a proper way. It looks more or less like:
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
struct some_const_struct {
const int arg1;
const int arg2;
};
class which_is_using_above_struct {
private:
some_const_struct* m_member;
const some_const_struct* const m_const_member;
public:
const some_const_struct& get_member() const { return *m_member; }
const some_const_struct& get_const_member() const { return *m_const_member; }
void set_member(const int a, const int b) {
if(m_member != NULL) {
delete m_member;
m_member = NULL;
}
m_member = new some_const_struct((some_const_struct){a, b});
}
explicit which_is_using_above_struct(const int a, const int b)
: m_const_member(new some_const_struct((const some_const_struct){a, b})) {
m_member = NULL;
}
~which_is_using_above_struct() {
if(m_member != NULL) {
delete m_member;
}
if(m_const_member != NULL) {
delete m_const_member;
}
}
};
int main() {
which_is_using_above_struct c(1, 2);
c.set_member(3, 4);
cout << "m_member.arg1 = " << c.get_member().arg1 << endl;
cout << "m_member.arg2 = " << c.get_member().arg2 << endl;
cout << "m_const_member.arg1 = " << c.get_const_member().arg1 << endl;
cout << "m_const_member.arg2 = " << c.get_const_member().arg2 << endl;
return 0;
}
I'm just not quite sure if the statement:
m_member = new some_const_struct((some_const_struct){a, b});
doesn't produce unnessesary use of some_const_struct's copy constructor, ergo allocating that struct twice. What do you think? And is it reasonable to make that struct's members const? (they're not supposed to change in their lifetime at all)
| m_const_member(new some_const_struct((const some_const_struct){a, b}))
Such syntax is not allowed by standard C++ and is only supported by your compiler as an extension.
I think the only standard-compiliant way with the current standard1 would be to use copy-construction and a helper function to initialize the struct in a portable way.2
inline some_const_struct make_some_const_struct(int a, int b)
{
some_const_struct x = {a, b};
return x;
}
//usage:
m_const_member(new some_const_struct(make_some_const_struct(a, b)))
I think you should just make your life easier and not use const members, particularly since set_member allows you to modify the fields anyway (at a great cost both coding- and performance-wise).
You could also give constructors3 to the classes, but then they won't be Plain Old Data structs any more, if that is important to you. (Actually I'm not sure whether a struct with const members qualifies as POD in the first place: e.g memsetting and memcpying such a struct would violate the constness of the members, but should be legal things to do with real POD structs.)
1 AFAIK, C++0x will revise the rules concerning {} in initialization, making it easier to achieve what you want.
2 Under favorable conditions, the compiler should be able to optimize out the needless copy, transforming it into the exact equivalent of what you are doing.
3 Comeau's compiler appears to be very helpful. It even tells you what (it thinks) you should do: warning: class "some_const_struct" defines no constructor to initialize the following: ...
|
2,793,774 | 2,793,782 | Error: Declaration terminated incorrectly | I get the error in this part of the code:
void baklanges(list<MataIn> lista);
{
int n = text.length();
for (int i = 0; i < n/2; i++) {
char temp = text.at(i);
text.at(i) = text.at(n-1-i);
text.at(n-1-i)= temp;
}
cout<<"Texten baklanges:\n"<<text<<endl;
}
I don't see any problem in the code,does any of you?
| Remove this semicolon.
void baklanges(list<MataIn> lista);
^
|
2,794,054 | 2,794,219 | Documenting functions in C++ with Doxygen | I've got a project that I'm using Doxygen to generate documentation for. The documentation of the classes is fine, but I've also got some non-member functions that I use to create objects etc. I'd also like to have these documented, but no matter what I try, Doxygen will not generate documentation from the comments that I have placed above the functions. Why won't Doxygen generate documentation for functions in the global namespace, and what do I need to do to get this to work?
| Use \fn where you otherwise use \class in your \\*! *\ block
http://www.doxygen.nl/manual/docblocks.html
look for "Documentation at other places"
http://www.doxygen.nl/manual/commands.html#cmdfn
It works similar as documenting member functions
|
2,794,079 | 2,794,105 | C++: Define simple constant for use? | In C++ I wanted to define a constant that I can use in another function, A short answer on how to do this will be fine..
Lets say at the beginning of my code I want to define this constant:
//After #includes
bool OS = 1; //1 = linux
if (OS) {
const ??? = "clear";
} else {
const ??? = "cls";
}
I don't know what type to use to define the "clear" string... I'm so confused.
Later on I want to use it within a function:
int foo() {
system(::cls); //:: for global
return 0;
}
How would I define the string up top, and use the string down below? I heard char only had one character and things... I'm not sure how to use , since it says it's converting string into const char or something.
| char* isn't quite a char. char* is basically a string (it's what strings were before C++ came along).
For illustration:
int array[N]; // An array of N ints.
char str[N]; // An array of N chars, which is also (loosely) called a string.
char[] degrades to char*, so you'll often see functions take a char*.
To convert std::string to const char*, you can simply call:
std::string s;
s.c_str()
In this case, it's common to use the preprocessor to define your OS. This way you can use the compiler to do the platform specific stuff:
#ifdef OS_LINUX
const char cls[] = "clear";
#elif OS_WIN
const char cls[] = "cls";
#endif
One thing you may want to consider is making it a function. This avoids nasty dependencies of global construction order.
string GetClearCommand() {
if (OS == "LINUX") {
return "clear";
} else if (OS == "WIN") {
return "cls";
}
FAIL("No OS specified?");
return "";
}
What it looks like you're trying to do is this:
#include <iostream>
using namespace std;
#ifdef LINUX
const char cls[] = "LINUX_CLEAR";
#elif WIN
const char cls[] = "WIN_CLEAR";
#else
const char cls[] = "OTHER_CLEAR";
#endif
void fake_system(const char* arg) {
std::cout << "fake_system: " << arg << std::endl;
}
int main(int argc, char** argv) {
fake_system(cls);
return 0;
}
// Then build the program passing your OS parameter.
$ g++ -DLINUX clear.cc -o clear
$ ./clear
fake_system: LINUX_CLEAR
|
2,794,369 | 2,794,481 | template class: ctor against function -> new C++ standard | in this question:
template; Point<2, double>; Point<3, double>
Dennis and Michael noticed the unreasonable foolishly implemented constructor.
They were right, I didn't consider this at that moment.
But I found out that a constructor does not help very much for a template class like this one, instead a function is here much more convenient and safe
namespace point {
template < unsigned int dims, typename T >
struct Point {
T X[ dims ];
std::string str() {
std::stringstream s;
s << "{";
for ( int i = 0; i < dims; ++i ) {
s << " X" << i << ": " << X[ i ] << (( i < dims -1 )? " |": " ");
}
s << "}";
return s.str();
}
Point<dims, int> toint() {
Point<dims, int> ret;
std::copy( X, X+dims, ret.X );
return ret;
}
};
template < typename T >
Point< 2, T > Create( T X0, T X1 ) {
Point< 2, T > ret;
ret.X[ 0 ] = X0; ret.X[ 1 ] = X1;
return ret;
}
template < typename T >
Point< 3, T > Create( T X0, T X1, T X2 ) {
Point< 3, T > ret;
ret.X[ 0 ] = X0; ret.X[ 1 ] = X1; ret.X[ 2 ] = X2;
return ret;
}
template < typename T >
Point< 4, T > Create( T X0, T X1, T X2, T X3 ) {
Point< 4, T > ret;
ret.X[ 0 ] = X0; ret.X[ 1 ] = X1; ret.X[ 2 ] = X2; ret.X[ 3 ] = X3;
return ret;
}
};
int main( void ) {
using namespace point;
Point< 2, double > p2d = point::Create( 12.3, 34.5 );
Point< 3, double > p3d = point::Create( 12.3, 34.5, 56.7 );
Point< 4, double > p4d = point::Create( 12.3, 34.5, 56.7, 78.9 );
//Point< 3, double > p1d = point::Create( 12.3, 34.5 ); //no suitable user defined conversion exists
//Point< 3, int > p1i = p4d.toint(); //no suitable user defined conversion exists
Point< 2, int > p2i = p2d.toint();
Point< 3, int > p3i = p3d.toint();
Point< 4, int > p4i = p4d.toint();
std::cout << p2d.str() << std::endl;
std::cout << p3d.str() << std::endl;
std::cout << p4d.str() << std::endl;
std::cout << p2i.str() << std::endl;
std::cout << p3i.str() << std::endl;
std::cout << p4i.str() << std::endl;
char c;
std::cin >> c;
}
has the new C++ standard any new improvements, language features or simplifications regarding this aspect of ctor of a template class?
what do you think about the implementation of the combination of namespace, stuct and Create function?
many thanks in advance
Oops
| Yes, as Michael pointed out in his answer to your previous question, in C++0x you'll be able to use an initializer list to pass an arbitrary number of arguments to your ctor. In your case, the code would look something like:
template <int dims, class T>
class point {
T X[dims];
public:
point(std::initializer_list<T> const &init) {
std::copy(init.begin(), init.begin()+dims, X);
}
};
You could create a point object with this something like:
point<3, double> x{0.0, 0.0, 0.0};
Personally, I'm not sure I like the basic design very well though. In particular, I'd rather see X turned into an std::vector, and determine the number of dimensions strictly from the parameter list that was passed instead of having it as a template argument:
template <class T>
class point {
std::vector<T> X;
public:
point(std::initializer_list<T> init) {
std::copy(init.begin(), init.end(), std::back_inserter(X));
}
};
This does have some trade-offs though -- points with a different number of dimensions are still the same type. For example, it basically asserts that it's reasonable to assign a 2D point to a 3D point, or vice versa.
|
2,794,385 | 2,794,400 | Is the "==" operator required to be defined to use std::find | Let's say I have:
class myClass
std::list<myClass> myList
where myClass does not define the == operator and only consists of public fields.
In both VS2010 and VS2005 the following does not compile:
myClass myClassVal = myList.front();
std::find( myList.begin(), myList.end(), myClassVal )
complaining about lack of == operator.
I naively assumed it would do a value comparison of the myClass object's public members, but I am almost positive this is not correct.
I assume if I define a == operator or perhaps use a functor instead, it will solve the problem.
Alternatively, if my list was holding pointers instead of values, the comparison would work.
Is this right or should I be doing something else?
| The compiler does not automatically generate a default operator==(), so if you don't write one yourself, objects of your class can't be compared for equality.
If you want memberwise comparison on the public members you have to implement that yourself as operator==() (or "manually" use a separate function/functor to do the comparison).
|
2,794,492 | 2,795,603 | How to tell what optimizations bjam is using to build boost | I'm building the boost libraries with bjam for both the intel compiler and vs2008, and I can't tell what optimizations are being passed to the compiler from bjam. For one of the compiler's gcc, I can see some optimizations in one of the bjam files, but I can't find the optimization flags for the compilers I care about. So, my questions are -
Does anyone know where the default optimization flags are located?
If they're declared within bjam, does anyone know how I can override them?
| If you are interested in looking at the entire set of options that are passed to invoke the compiler when building you can run bjam with the -n -a options and the rest of the building options to give you the complete set of commands invoked, and any response files generated (see Boost Jam Options). Also you can look at the Boost Build sources directly and see what the specified features are translated into (see Boost Build Tools Files). For example:
For GCC see gcc.jam
For MSVC see msvc.jam
You can likely figure out the same for other compilers by just looking through the sources as they are fairly self explanatory. And you can just search for "<optimization>" and "<inlining>" in the *.jam sources.
You can override them in the command line by specifying the feature=value option in the command line when building. The options match the <feature>value specifications you see in the toolset files. For example, to override the optimizations feature you would specify in the command line some like "optimization=speed". If you want more fine grained control you would have to delve into Boost Build specifications and likely have to create a variant of your own to define specific options and features to build with.
|
2,794,596 | 2,794,844 | Sequential File Access, load multiple text files in project directory using C++ | Is it possible to load multiple files from a project directory. For example, loading FileA.txt, FileB.txt, and FileC.txt from a folder (raw/assets) within the project folder?
Any help would be much appreciated.
| Since your comment says you're targetting Windows, take a look at this API function:
http://msdn.microsoft.com/en-us/library/aa364418%28VS.85%29.aspx
Find files matching your pattern and deal with them
http://www.cplusplus.com/doc/tutorial/files/
|
2,794,637 | 2,794,658 | How to easily substitute a Base class | I have the following hierarchy of classes
class classOne
{
virtual void abstractMethod() = 0;
};
class classTwo : public classOne
{
};
class classThree : public classTwo
{
};
All classOne, classTwo and classThree are abstract classes, and I have another class that is defining the pure virtual methods
class classNonAbstract : public classThree
{
void abstractMethod();
// Couple of new methods
void doIt();
void doItToo();
};
And right now I need it differently...I need it like
class classNonAbstractOne : public classOne
{
void abstractMethod();
// Couple of new methods
void doIt();
void doItToo();
};
class classNonAbstractTwo : public classTwo
{
void abstractMethod();
// Couple of new methods
void doIt();
void doItToo();
};
and
class classNonAbstractThree : public classThree
{
void abstractMethod();
// Couple of new methods
void doIt();
void doItToo();
};
But all the nonAbstract classes have the same new methods, with the same code...and I would like to avoid copying all the methods and it's code to every nonAbstract class. How could I accomplish that?
Hopefully it's understandable...
| template<class Base>
struct Concrete : Base {
void abstractMethod();
void doIt() {
// example of accessing inherited members:
int n = Base::data_member; // or this->data_member
n = Base::method(); // non-virtual dispatch
n = this->method(); // virtual dispatch
// since Base is a template parameter, 'data_member' and 'method' are
// dependent names and using them unqualified will not properly find
// them
}
void doItToo();
};
typedef Concrete<classOne> classNonAbstractOne; // if desired, for convenience
Make sure to give your abstract base classes either a virtual public destructor or make the destructor protected (then it doesn't have to be virtual, but still can be).
Because the template must be parsed with names looked up without yet knowing exactly what Base will be, you need to either use Base::member or this->member to access inherited members.
|
2,794,825 | 2,794,889 | boost::lambda bind expressions can't get bind to string's empty() to work | I am trying to get the below code snippet to compile. But it fails with:
error C2665: 'boost::lambda::function_adaptor::apply' : none of the 8 overloads could convert all the argument types. Specifying the return type when calling bind does not help.
Any idea what I am doing wrong?
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <string>
#include <map>
int main()
{
namespace bl = boost::lambda;
typedef std::map<int, std::string> types;
types keys_and_values;
keys_and_values[ 0 ] = "zero";
keys_and_values[ 1 ] = "one";
keys_and_values[ 2 ] = "Two";
std::for_each(
keys_and_values.begin(),
keys_and_values.end(),
std::cout << bl::constant("Value empty?: ") << std::boolalpha <<
bl::bind(&std::string::empty,
bl::bind(&types::value_type::second, _1)) << "\n");
return 0;
}
| minor changes to make it compile with g++ (time for better compiler :-) ?)
1 #include <boost/lambda/lambda.hpp>
2 #include <boost/lambda/bind.hpp>
3 #include <algorithm>
4 #include <iostream>
5 #include <string>
6 #include <map>
7
8 int main()
9 {
10
11 namespace bl = boost::lambda;
12 typedef std::map<int, std::string> types;
13 types keys_and_values;
14 keys_and_values[ 0 ] = "zero";
15 keys_and_values[ 1 ] = "one";
16 keys_and_values[ 2 ] = "Two";
17
18 std::for_each(
19 keys_and_values.begin(),
20 keys_and_values.end(),
21 std::cout << bl::constant("Value empty?: ") << std::boolalpha <<
22 bl::bind(&std::string::empty,
23 bl::bind(&types::value_type::second, bl::_1)) << "\n");
24
25
26
27
28 return 0;
29 }
notice missing includes and bl::_1
|
2,794,916 | 2,794,919 | Pre-compile .h files | I have a really short program written in boost::xpressive
#include <iostream>
#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive;
int main()
{
std::string hello( "hello world!" );
sregex rex = sregex::compile( "(\\w+) (\\w+)!" );
smatch what;
if( regex_match( hello, what, rex ) )
{
std::cout << what[0] << '\n'; // whole match
std::cout << what[1] << '\n'; // first capture
std::cout << what[2] << '\n'; // second capture
}
return 0;
}
It's the Xpressive "hello world". It takes significantly longer than an ordinary hello world to compile. I think it's because the xpressive.hpp file is so huge. Is there a way to pre-compile or pre-process the .hpp file so the compile will be much faster?
| You can use precompiled headers if your compiler supports them; both g++ and Visual C++ support precompiled headers, as do most other modern C++ compilers, I suspect.
|
2,794,956 | 2,794,962 | C++ Namespaces & templates | I have some functions that can be grouped together, but don't belong to some object / entity and therefore can't be treated as methods.
So, basically in this situation I would create a new namespace and put the definitions in a header file, the implementation in cpp file. Also (if needed) I would create an anonymous namespace in that cpp file and put all additional functions that don't have to be exposed / included to my namespace's interface there.
See the code below (probably not the best example and could be done better with another program architecture, but I just can't think of a better sample...)
Sample code (header)
namespace algorithm {
void HandleCollision(Object* object1, Object* object2);
}
Sample code (cpp)
#include "header"
// Anonymous namespace that wraps
// routines that are used inside 'algorithm' methods
// but don't have to be exposed
namespace {
void RefractObject(Object* object1) {
// Do something with that object
// (...)
}
}
namespace algorithm {
void HandleCollision(Object* object1, Object* object2) {
if (...) RefractObject(object1);
}
}
So far so good. I guess this is a good way to manage my code, but I don't know what should I do if I have some template-based functions and want to do basically the same.
If I'm using templates, I have to put all my code in the header file. Ok, but how should I conceal some implementation details then?
I want to hide RefractObject function from my interface, but I can't simply remove its declaration (just because I have all my code in a header file)...
The only approach I came up with was something like:
Sample code (header)
namespace algorithm {
// Is still exposed as a part of interface!
namespace impl {
template <typename T>
void RefractObject(T* object1) {
// Do something with that object
// (...)
}
}
template <typename T, typename Y>
void HandleCollision(T* object1, Y* object2) {
impl::RefractObject(object1);
// Another stuff
}
}
Any ideas how to make this better in terms of code designing?
| That's a pretty common solution. Boost does it, and I do it as well, but with the detail namespace instead. Just make it a rule: "don't look inside detail!"
File-wise, I recommend giving details their own file, and tucking it away in a detail folder. That is, my code would be akin to:
// v
#include "detail/RefractObject.hpp"
namespace algorithm {
template <typename T, typename Y>
void HandleCollision(T* object1, Y* object2) {
detail::RefractObject(object1);
// Another stuff
}
}
This is just good code practice in general (keep things split up and re-usable) and keeps the header file cleaner of implementation details.
|
2,795,023 | 2,795,024 | C++ template typedef | I have a class
template<size_t N, size_t M>
class Matrix {
// ....
};
I want to make a typedef which creates a Vector (column vector) which is equivalent to a Matrix with sizes N and 1. Something like that:
typedef Matrix<N,1> Vector<N>;
Which produces compile error. The following creates something similar, but not exactly what I want:
template <size_t N>
class Vector: public Matrix<N,1>
{ };
Is there a solution or a not too expensive workaround / best-practice for it?
| C++11 added alias declarations, which are generalization of typedef, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3> is equivalent to Matrix<3, 1>.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.
|
2,795,237 | 2,795,292 | it takes 2 seconds to compile a hello world C++ project in netbeans (windows) | I used code:blocks as the C++ IDE on Windows. I switched to netbeans 6.8 (with C/C++ plugin, MinGW, MSYS) recently, because netbeas have the nice feature of "checking syntax errors when typing" (same as working on Java or PHP projects).
But the painful thing is that, it takes 2 seconds to compile a simple hello world project in netbeans. Any trick to make it as fast as code:blocks, or at least make the compiling time no more than 0.5 second?
EDIT:
I did not care about this 2 seconds difference until I worked on Google codejam questions yesterday.
| MinGW uses G++ 3.x, which is very very old. It's a limitation of the compiler itself -- old versions of G++ are simply slow. There are some "unofficial" G++ ports to windows that borrow from the MinGW project that use more recent (4.x) versions of G++, and it's possible your Code::Blocks IDE was using one of those.
I seriously doubt that the second and a half is significant in 99.9% of usages of most compilers anyway. Even if it is overhead imposed by the IDE itself, we're talking about what is essentially a one time cost -- it shouldn't blow up to insane compile times when you compile larger programs.
In response to FredOverflow's comment: From the MinGW installer (mingw.ini):
[mingw]
Build=12
URL=http://prdownloads.sourceforge.net/mingw
Filename=MinGW-5.1.6.exe
packages=previous|current|candidate
[current]
runtime=mingwrt-3.17-mingw32-dev.tar.gz|7300
runtimeDLL=mingwrt-3.17-mingw32-dll.tar.gz|30
w32api=w32api-3.14-mingw32-dev.tar.gz|14460
binutils=binutils-2.20-1-mingw32-bin.tar.gz|26979
core=gcc-core-3.4.5-20060117-3.tar.gz|7712
gpp=gcc-g++-3.4.5-20060117-3.tar.gz|15480
g77=gcc-g77-3.4.5-20060117-3.tar.gz|5272
ada=gcc-ada-3.4.5-20060117-3.tar.gz|33860
java=gcc-java-3.4.5-20060117-3.tar.gz|43160
objc=gcc-objc-3.4.5-20060117-3.tar.gz|3720
make=make-3.81-20090914-mingw32-bin.tar.gz|723
[previous]
runtime=mingwrt-3.15.2-mingw32-dev.tar.gz|7616
runtimeDLL=mingwrt-3.15.2-mingw32-dll.tar.gz|40
w32api=w32api-3.13-mingw32-dev.tar.gz|14420
binutils=binutils-2.19.1-mingw32-bin.tar.gz|21093
core=gcc-core-3.4.2-20040916-1.tar.gz|8627
gpp=gcc-g++-3.4.2-20040916-1.tar.gz|16542
g77=gcc-g77-3.4.2-20040916-1.tar.gz|5158
ada=gcc-ada-3.4.2-20040916-1.tar.gz|33333
java=gcc-java-3.4.2-20040916-1.tar.gz|45547
objc=gcc-objc-3.4.2-20040916-1.tar.gz|4555
make=mingw32-make-3.81-20080326-2.tar.gz|727
[candidate]
binutils=binutils-2.18.50-20080109-2.tar.gz|20505
core=gcc-core-3.4.5-20060117-3.tar.gz|7712
gpp=gcc-g++-3.4.5-20060117-3.tar.gz|15480
g77=gcc-g77-3.4.5-20060117-3.tar.gz|5272
ada=gcc-ada-3.4.5-20060117-3.tar.gz|33860
java=gcc-java-3.4.5-20060117-3.tar.gz|43160
objc=gcc-objc-3.4.5-20060117-3.tar.gz|3720
make=mingw32-make-3.81-2.tar.gz|720
|
2,795,243 | 2,795,273 | Error in function prototype | Why does this code result in error?
class CommonRuntine
{
public:
struct TProcess;
TProcess GetProcessByName(LPCSTR ProcessName);
};
It says "E2293 ) Expected" on the "};" bit
PS : LPCSTR is a type
| #include <windows.h>
Had to include the file defining that type
|
2,795,309 | 2,877,835 | How do you parse the XDG/gnome/kde menu/desktop item structure in c++? | I would like to parse the menu structure for Gnome Panels (the standard Gnome Desktop application launcher) and it's KDE equivalent using c/c++ function calls. That is, I'd like a list of what the base menu categories and submenu are installed in a given machine. I would like to do with using fairly simple c/c++ function calls (with NO shelling out please).
I understand that these menus are in the standard xdg format.
I understand that this menu structure is stored in xml files such as:
/home/user/.config/menus/applications.menu
I've looked here: http://www.freedesktop.org/wiki/Specifications/menu-spec?action=show&redirect=Standards%2Fmenu-spec but all they offer is the standard and some shell files to insert item entries (I don't want shell scripts, I don't want installation, I definitely don't want to create a c-library from the XDG specification. I want to find the existing menu structure). I've looked here: http://library.gnome.org/admin/system-admin-guide/stable/menustructure-13.html.en for more notes on these structures. None of this gives me a good idea of how determine the menu structures using a c/c++ program.
The actual gnome menu structures seem to be a horrifically hairy things - they don't seem to show the menu structure but to give an XML-coded description of all the changes that the menus have gone through since installation. I assume gnome panels parses these file so there's a function buried somewhere to do this but I've yet to find where that function is after scanning library.gnome.org for a couple of days. I've scanned the Nautilus source code as well but Panels seem to exist elsewhere or are burried well.
Thanks in advance
| After much painful research... it seems the most stable approach is to take the gnome menu parsing code, rip it of the tar ball and use it locally.
The version I used is here:
http://download.gnome.org/sources/gnome-menus/2.28/gnome-menus-2.28.0.1.tar.gz
This code loudly proclaims that it shouldn't treated as any kind of API so one is forced to, as I said rip it of the gnome tree and keep a local copy for one's own application (gather than dynamically linking to a library).
The KDE version of the menu-parsing code seems like it could be used more transportably but actually depends heavily on KDE's virtual file system. As far as I can tell, the code gnome works stand-alone. The test-file can serve as a template for doing your own parsing.
|
2,795,395 | 2,803,171 | controling individual pins on a serial port | I know that serial ports work by sending a single stream of bits in serial. I can write programs to send and receive data from that one pin.
However, there are a lot more other pins on the serial port connection that normal aren't used but from documentation all seem to have some sort of function for signalling as opposed to data transfer.
Is it possible in any way to cause the other pins that are not used for direct data transfer to be controlled individually? If so, how would i go about doing that?
EDIT: more information
I am working with a modern CPU running windows 7 64-bit on an intel core i7 870 processor. I'm using serial to usb ports because its imposable for me to do anything directly with a usb port and my computer does not come with serial ports and also for some inexplicable reason i have a bunch of these usb to serial port adapters lying around.
My goal is to control mutipul stepper motors (200 steps per rotation, 4 phase motors). My simple circuitry accepts single high pulses and interprets it as a command to cause the motor to rotate one step. The circuit itself will handle the power supply and phase switching. I wish to use the data transfer pin to send the rotation signals (we can control position and velocity by altering the number of high pulses and frequency of high pulses through the pin, however there is no real pulse width modulation).
I have many motors to control but they do not need to be controlled simultaneously. I hope to use the rest of the pins and run them through a simple combination logic circuit to identify which motor is being moved and which direction it is to move in. This is part of the power switching circuitry.
The data transfer pin will operate normally at some low end frequency. However, i want to control the other pins to allow me to give a solid on or off signal (they wont be flipping very quickly, only changes when i switch to controlling another motor).
| Based of the suggestion of Hans Passant , I'd like to suggest that you use an Arduino instead of an USB-to-serial converter. The "Duemilanove" is an Arduino-based board that provides 6 PWM outputs (as well as 8 other digitial I/Os and 6 analog). Some more specialized boards might be even cheaper (Arduino Pro Mini, $15 in volume, some soldering required).
|
2,795,443 | 2,795,469 | What's the difference between the terms "source file" and "translation unit"? | What's the difference between source file and translation unit?
| From the C++ Standard:
A source file together with all the headers and source files included via the preprocessing directive #include less any source line skipped by any of the conditional inclusion preprocessing directives is called a translation unit.
|
2,795,466 | 2,795,476 | Converting a time_t to string | I have a time_t variable containing a timestamp which I'd like to store in a database, so I need it as a string. How would I convert it?
Also, on the subject, how would I convert a timestamp string into a time_t variable?
Thanks,
Wyatt
| Look at ctime, it takes a time_t and returns a string.
To make a timestamp from a string, look at mktime. Populate the fields of a struct tm and call mktime. It should return a time_t.
|
2,795,482 | 2,795,510 | Is there a cross-platform header in the standard library that provides access to the current time? | Probably a stupid question, but I couldn't find anything searching...
Is there a standard header that allows me to fetch the current time? Otherwise is there some cross-platform alternative?
| time.h, and the time function.
|
2,795,528 | 2,812,701 | Bluetooth service problem | I need to create a custom bluetooth service and I have to develop it using c++. I read a lot of examples but I didn't success in publishing a new service with a custom UUID. I need to specify a UUID in order to be able to connect to the service from an android app. This is what i wrote:
GUID service_UUID = { /* 00000003-0000-1000-8000-00805F9B34FB */
0x00000003,
0x0000,
0x1000,
{0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB}
};
SOCKET s, s2;
SOCKADDR_BTH sab
if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
return 1;
printf("installing a new service\n");
s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (s == INVALID_SOCKET)
{
printf ("Socket creation failed, error %d\n", WSAGetLastError());
return 1;
}
memset (&sab, 0, sizeof(sab));
sab.addressFamily = AF_BTH;
sab.port = BT_PORT_ANY;
sab.serviceClassId = service_UUID;
if (0 != bind(s, (SOCKADDR *) &sab, sizeof(sab)))
{
printf ("bind() failed with error code %d\n", WSAGetLastError());
closesocket (s);
return 1;
}
int result=sizeof(sab);
getsockname(s,(SOCKADDR *) &sab, &result );
printSOCKADDR_BTH(sab);
if(listen (s, 5) == 0)
printf("listen() is OK! Listening for connection... :)\n");
else
printf("listen() failed with error code %d\n", WSAGetLastError());
printf("waiting connection");
for ( ; ; )
{
int ilen = sizeof(sab2);
s2 = accept (s, (SOCKADDR *)&sab2, &ilen);
printf ("accepted");
}
if(closesocket(s) == 0)
printf("closesocket() pretty fine!\n");
if(WSACleanup () == 0)
printf("WSACleanup() is OK!\n");
return 0;
When i print the SOCKADDR_BTH structure retrieved with get getsockname i get an UUID that is not the mine. Furthermore if i use the UUID read from getsockname to connect the Android application the connection fails with this exception:
java.io.IOException: Service discovery failed
Could you help me??
Thanks!
| You have to create the SDP record and publish it with WSASetService before bind and wait for connections.
Follow this tutorial, and you'll be able to receive connections.
|
2,795,575 | 2,795,596 | How does dereferencing of a function pointer happen? | Why and how does dereferencing a function pointer just "do nothing"?
This is what I am talking about:
#include<stdio.h>
void hello() { printf("hello"); }
int main(void) {
(*****hello)();
}
From a comment over here:
function pointers dereference just
fine, but the resulting function
designator will be immediately
converted back to a function pointer
And from an answer here:
Dereferencing (in way you think) a
function's pointer means: accessing a
CODE memory as it would be a DATA
memory.
Function pointer isn't suppose to be
dereferenced in that way. Instead, it
is called.
I would use a name "dereference" side
by side with "call". It's OK.
Anyway: C is designed in such a way
that both function name identifier as
well as variable holding function's
pointer mean the same: address to CODE
memory. And it allows to jump to that
memory by using call () syntax either
on an identifier or variable.
How exactly does dereferencing of a function pointer work?
| It's not quite the right question. For C, at least, the right question is
What happens to a function value in an rvalue context?
(An rvalue context is anywhere a name or other reference appears where it should be used as a value, rather than a location — basically anywhere except on the left-hand side of an assignment. The name itself comes from the right-hand side of an assignment.)
OK, so what happens to a function value in an rvalue context? It is immediately and implicitly converted to a pointer to the original function value. If you dereference that pointer with *, you get the same function value back again, which is immediately and implicitly converted into a pointer. And you can do this as many times as you like.
Two similar experiments you can try:
What happens if you dereference a function pointer in an lvalue context—the left-hand side of an assignment. (The answer will be about what you expect, if you keep in mind that functions are immutable.)
An array value is also converted to a pointer in an lvalue context, but it is converted to a pointer to the element type, not to a pointer to the array. Dereferencing it will therefore give you an element, not an array, and the madness you show doesn't occur.
Hope this helps.
P.S. As to why a function value is implicitly converted to a pointer, the answer is that for those of us who use function pointers, it's a great convenience not to have to use &'s everywhere. There's a dual convenience as well: a function pointer in call position is automatically converted to a function value, so you don't have to write * to call through a function pointer.
P.P.S. Unlike C functions, C++ functions can be overloaded, and I'm not qualified to comment on how the semantics works in C++.
|
2,795,609 | 2,795,611 | How does #error in C/C++ work? | I am guessing from # that it is only a compile-time utility. How can it be used in C/C++ programs?
Did not find much about it on the internet. Any links would be helpful.
| It causes the compiler (or preprocessor) to output the error message. In C++, it also renders the translation unit ill-formed (i.e., it causes compilation to fail).
If you have several macros that could be defined and you want to be sure that only certain combinations of them are defined, you can use #error to cause compilation to fail if an invalid combination is defined.
It can also be useful if you want to be sure that some block of code is never compiled (for whatever reason).
|
2,795,943 | 2,795,955 | How to iterate properly across a const set? | I'm working on a program that's supposed to represent a graph. My issue is in my printAdjacencyList function. Basically, I have a Graph ADT that has a member variable "nodes", which is a map of the nodes of that graph. Each Node has a set of Edge* to the edges it is connected to. I'm trying to iterate across each node in the graph and each edge of a node.
void MyGraph::printAdjacencyList() {
std::map<std::string, MyNode*>::iterator mit;
std::set<MyEdge*>::iterator sit;
for (mit = nodes.begin(); mit != nodes.end(); mit++ ) {
std::cout << mit->first << ": {";
const std::set<MyEdge*> edges = mit->second->getEdges();
for (sit = edges.begin(); sit != edges.end(); sit++) {
std::pair<MyNode*, MyNode*> edgeNodes = *sit->getEndpoints();
}
}
std::cout << " }" << std::endl;
}
getEdges is declared as:
const std::set<MyEdge*>& getEdges() { return edges; };
and get Endpoints is declared as:
const std::pair<MyNode*, MyNode*>& getEndpoints() { return nodes; };
The compiler error I'm getting is:
MyGraph.cpp:63: error: request for member `getEndpoints' in
`*(&sit)->std::_Rb_tree_const_iterator<_Tp>::operator->
[with _Tp = MyEdge*]()', which is of non-class type `MyEdge* const'
MyGraph.cpp:63: warning: unused variable 'edgeNodes'
I have figured out that this probably means I'm misusing const somewhere, but I can't figure out where for the life of me. Any information would be appreciated. Thanks!
| Try changing sit to a const_iterator. Change mit to a const_iterator too while you're at it. Also, getEdges() and getEndpoints() should be const functions. Lastly, because operator->() has a higher precedence than the unary operator*(), you probably want to say edgeNodes = (*sit)->getEndPoints() inside the inner-loop.
Not as much of a problem but you should consider having the iterator instances as local to the loops.
|
2,795,964 | 2,795,999 | Getting a unix timestamp as a string in C++ | I'm using the function time() in order to get a timestamp in C++, but, after doing so, I need to convert it to a string. I can't use ctime, as I need the timestamp itself (in its 10 character format). Trouble is, I have no idea what form a time_t variable takes, so I don't know what I'm converting it from. cout handles it, so it must be a string of some description, but I have no idea what.
If anyone could help me with this it'd be much appreciated, I'm completely stumped.
Alternately, can you provide the output of ctime to a MySQL datetime field and have it interpreted correctly? I'd still appreciate an answer to the first part of my question for understanding's sake, but this would solve my problem.
| time_t is some kind of integer. If cout handles it in the way you want, you can use a std::stringstream to convert it to a string:
std::string timestr(time_t t) {
std::stringstream strm;
strm << t;
return strm.str();
}
|
2,796,016 | 2,796,340 | Specify an inline callback function as an argument | Let me first explain what I'm trying to achieve using some pseudo-code (JavaScript).
// Declare our function that takes a callback as as an argument, and calls the callback with true.
B(func) { func(true); }
// Call the function
B(function(bool success) { /* code that uses success */ });
I hope this says it all. If not, please comment on my question so I can write a little more to clarify my issue.
What I want is to have code like this in C++.
I have tried to use lambda functions, but I was unable to specify a parameter type for those.
| If your compiler is a fairly recent release (such as Visual Studio 2010 or GCC 4.5), you can use some new features from the new C++ standard, which is currently in ratification and should be published soon.
I don't know what you need to do to enable this in Visual Studio, but it should be well-documented either on MSDN or internal help.
For GCC 4.5, just add the -std=c++0x option to enable the new features.
One of these features is the Lambda syntax:
template <typename F>
void func_with_callback(F f) {
f(true);
}
int main() {
func_with_callback( [](bool t){ if(t) cout << "lambda called" << endl; } );
}
If you don't have access to a modern compiler, you can use techniques such as functors and libraries like boost::lambda, which can perform similarly.
|
2,796,223 | 2,796,235 | Copying from istream never stops | This bit of code runs infinitely:
copy(istream_iterator<char>(cin), istream_iterator<char>(), back_inserter(buff));
The behavior I was expecting is that it will stop when I press enter.
However it doesn't.
buff is a vector of chars.
| I assume you are typing stuff in at the keyboard.
The enter key doesn't signify the end of the stream. It's just another character from cin's perspective. You need to submit EOF to achieve this (Ctrl+Z, Enter on Windows and Ctrl+D on Unix/Mac).
Incidentally, this isn't the usual way to read characters from the console. It is very inefficient (istream_iterator calls operator>> for each character) and will misbehave with whitespace. To read a line of data entry, use getline instead.
|
2,796,413 | 2,796,504 | Binary search to find the rotation point in a rotated sorted list | I have a sorted list which is rotated and would like to do a binary search on that list to find the minimum element.
Lets suppose initial list is {1,2,3,4,5,6,7,8}
rotated list can be like {5,6,7,8,1,2,3,4}
Normal binary search doesn't work in this case. Any idea how to do this.
-- Edit
I have one another condition. What if the list is not sorted??
| A slight modification on the binary search algorithm is all you need; here's the solution in complete runnable Java (see Serg's answer for Delphi implementation, and tkr's answer for visual explanation of the algorithm).
import java.util.*;
public class BinarySearch {
static int findMinimum(Integer[] arr) {
int low = 0;
int high = arr.length - 1;
while (arr[low] > arr[high]) {
int mid = (low + high) >>> 1;
if (arr[mid] > arr[high]) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
public static void main(String[] args) {
Integer[] arr = { 1, 2, 3, 4, 5, 6, 7 };
// must be in sorted order, allowing rotation, and contain no duplicates
for (int i = 0; i < arr.length; i++) {
System.out.print(Arrays.toString(arr));
int minIndex = findMinimum(arr);
System.out.println(" Min is " + arr[minIndex] + " at " + minIndex);
Collections.rotate(Arrays.asList(arr), 1);
}
}
}
This prints:
[1, 2, 3, 4, 5, 6, 7] Min is 1 at 0
[7, 1, 2, 3, 4, 5, 6] Min is 1 at 1
[6, 7, 1, 2, 3, 4, 5] Min is 1 at 2
[5, 6, 7, 1, 2, 3, 4] Min is 1 at 3
[4, 5, 6, 7, 1, 2, 3] Min is 1 at 4
[3, 4, 5, 6, 7, 1, 2] Min is 1 at 5
[2, 3, 4, 5, 6, 7, 1] Min is 1 at 6
See also
Java Collections.rotate() with an array doesn’t work
Explains why Integer[] instead of int[]
Google Research Blog: Nearly All Binary Searches and Mergesorts are Broken
Explains why >>> 1 instead of / 2
On duplicates
Note that duplicates makes it impossible to do this in O(log N). Consider the following bit array consisting of many 1, and one 0:
(sorted)
01111111111111111111111111111111111111111111111111111111111111111
^
(rotated)
11111111111111111111111111111111111111111111101111111111111111111
^
(rotated)
11111111111111101111111111111111111111111111111111111111111111111
^
This array can be rotated in N ways, and locating the 0 in O(log N) is impossible, since there's no way to tell if it's in the left or right side of the "middle".
I have one another condition. What if the list is not sorted??
Then, unless you want to sort it first and proceed from there, you'll have to do a linear search to find the minimum.
See also
Wikipedia | Selection algorithm | Linear minimum/maximum algorithms
|
2,796,726 | 2,796,735 | copying a substring from a string given end index in string | How can I copy a substring from a given string with start and end index or giving the start index and length of the string are given.
| From a std::string, std::string::substr will create a new std::string from an existing one given a start index and a length. It should be trivial to determine the necessary length given the end index. (If the end index is inclusive instead of exclusive, some extra care should be taken to ensure that it is a valid index into the string.)
If you're trying to create a substring from a C-style string (a NUL-terminated char array), then you can use the std::string(const char* s, size_t n) constructor. For example:
const char* s = "hello world!";
size_t start = 3;
size_t end = 6; // Assume this is an exclusive bound.
std::string substring(s + start, end - start);
Unlike std::string::substr, the std::string(const char* s, size_t n) constructor can read past the end of the input string, so in this case you also should verify first that the end index is valid.
|
2,796,966 | 2,797,808 | `.' cannot appear in a constant-expression | I'm getting the following error:
`.' cannot appear in a constant-expression
for this function (line 4):
bool Covers(const Region<C,V,D>& other) const {
const Region& me = *this;
for (unsigned d = 0; d < D; d++) {
if (me[d].min > other[d].min || me[d].max < other[d].max) {
return false;
}
}
can anyone explain the problem please?
EDIT:
the definition of Region is:
template <typename C, typename V, unsigned D>
class Region : public boost::array<Detail::Range<C>,D>
when Range has a min and max variables.
| Trying out your code tells me, that the compiler has a problem with the me[d].max < other[d].max part. So the problem with the dot was bogus. Instead the compiler has a problem with the comparison operator. Just reverting the comparison made the compiler error magically disappear:
if (me[i].min > other[i].min || other[i].max > me[i].max) {
return false;
}
|
2,797,014 | 2,797,022 | Why can't I reserve 1,000,000,000 in my vector? | When I type in the foll. code, I get the output as 1073741823.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> v;
cout<<v.max_size();
return 0;
}
However when I try to resize the vector to 1,000,000,000, by v.resize(1000000000); the program stops executing. How can I enable the program to allocate the required memory, when it seems that it should be able to?
I am using MinGW in Windows 7. I have 2 GB RAM. Should it not be possible?
In case it is not possible, can't I declare it as an array of integers and get away? BUt even that doesn't work.
Another thing is that, suppose I would use a file(which can easily handle so much data ).
How can I let it read and write and the same time.
Using fstream file("file.txt', ios::out | ios::in ); doesn't create a file, in the first place. But supposing the file exists, I am unable to use to do reading and writing simultaneously.
WHat I mean is this :
Let the contents of the file be 111111
Then if I run : -
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream file("file.txt",ios:in|ios::out);
char x;
while( file>>x)
{
file<<'0';
}
return 0;
}
Shouldn't the file's contents now be 101010 ? Read one character and then overwrite the next one with 0 ? Or incase the entire contents were read at once into some buffer, should there not be atleast one 0 in the file ? 1111110 ?
But the contents remain unaltered. Please explain.
Thank you.
|
A 32-bit process can only address 4GB address space at a single time. Usually, plenty of this 4GB address space is used to map other stuff. Your vector is going to take too much contiguous address space (4 billion bytes) which is not likely to be available.
You should memory map the file. See mmap.
|
2,797,208 | 2,797,233 | How union is used to define a class | I have two doubts, please help me on this:
Is it possible to define a class inside union
Is it possible to define a class without class name
| 1 - yes with restriction that class has no constructor or destructor
2 - yes
Following code aggregates both as an example:
union MyUnion
{
class
{
public:
int a;
int b;
} anonym_access;
double align;
};
int main()
{
MyUnion u; //instance checks if it is compileable
}
|
2,797,366 | 2,839,111 | Win32 Thread Exits Unexpectedly | I'm writing a C++ application. I realized that one of my worker threads may terminate unexpectedly. The (VS 2005) debug log says:
The thread 'Win32 Thread' (0x5d98) has
exited with code -858993460
(0xcccccccc).
I surrounded all the worker thread code with a try/catch block. So, if the reason was an exception, I would catch it. But I can't:
try{
...
Connection* conn = connectionPool->getConnection(); // unexpected exit occurs here
...
} catch(exception& e) {
...
}
I have ten threads running concurrently, and only one of them gets crashed after some time, while the others continue running (and getting new [OCCI] connections).
Is there an exception type that is not caught by "exception"? Or what do I not know about threads/exceptions?
Thanks.
| I found an important clue. When you close a handle with CloseHandle function, the thread exits with code 0xCCCCCCCC. With the help of this clue, I realized that in a very rare situation, I close my thread's handle even though the thread's working. Why does it exit exactly while getting connection? That also has an explanation, but it's related to the structure of the code, which may be difficult to explain here.
Thank you all, who brainstormed with me on the exceptions issue :$.
|
2,797,390 | 2,797,638 | C callback functions defined in an unnamed namespace? | I have a C++ project that uses a C bison parser. The C parser uses a struct of function pointers to call functions that create proper AST nodes when productions are reduced by bison:
typedef void Node;
struct Actions {
Node *(*newIntLit)(int val);
Node *(*newAsgnExpr)(Node *left, Node *right);
/* ... */
};
Now, in the C++ part of the project, i fill those pointers
class AstNode {
/* ... */
};
class IntLit : public AstNode {
/* ... */
};
extern "C" {
Node *newIntLit(int val) {
return (Node*)new IntLit(val);
}
/* ... */
}
Actions createActions() {
Actions a;
a.newIntLit = &newIntLit;
/* ... */
return a;
}
Now the only reason i put them within extern "C" is because i want them to have C calling conventions. But optimally, i would like their names still be mangled. They are never called by-name from C code, so name mangling isn't an issue. Having them mangled will avoid name conflicts, since some actions are called like error, and the C++ callback function has ugly names like the following just to avoid name clashes with other modules.
extern "C" {
void uglyNameError(char const *str) {
/* ... */
}
/* ... */
}
a.error = &uglyNameError;
I wondered whether it could be possible by merely giving the function type C linkage
extern "C" void fty(char const *str);
namespace {
fty error; /* Declared! But i can i define it with that type!? */
}
Any ideas? I'm looking for Standard-C++ solutions.
| I don't get the problem. The extern keyword does not affect the calling convention, merely the name presented to the linker. A function written in C++ that is not an instance method is still __cdecl, with or without extern "C". Furthermore, as long as you keep createActions() in the same source code file, these functions don't need external linkage. You could declare them static or put them in an unnamed namespace to avoid collisions.
|
2,797,391 | 2,797,439 | Singleton with inheritance, Derived class is not able to get instantiated in parent? | Below code instantiates a derived singleton object based on environment variable. The compiler errors saying error C2512: 'Dotted' : no appropriate default constructor. I don't understand what the compiler is complaining about.
EDIT:
Fixed issues with implementing the get instance method which requires definition of both the parent and derived class. By separating the class definitions in separate header files and including the same in Singleton.cpp where the instance function is implemented.
Mainfile – 1
#include <iostream>
#include <string>
#include "Singleton.h"
using namespace std;
int main(){
Singleton::instant().print();
cin.get();
}
Singleton.h
#pragma once
#include <iostream>
using std::cout;
class Singleton{
public:
static Singleton & instant();
virtual void print(){cout<<"Singleton";}
protected:
Singleton(){};
private:
static Singleton * instance_;
Singleton(const Singleton & );
void operator=(const Singleton & );
};
Singleton.cpp
#include "Singleton.h"
#include "Dotted.h"
Singleton * Singleton::instance_ = 0;
Singleton & Singleton::instant(){
if (!instance_)
{
char * style = getenv("STYLE");
if (style){
if (strcmp(style,"dotted")==0)
{
instance_ = new Dotted();
return *instance_;
} else{
instance_ = new Singleton();
return *instance_;
}
}
else{
instance_ = new Singleton();
return *instance_;
}
}
return *instance_;
}
Dotted.h
#pragma once
class Dotted;
class Dotted:public Singleton{
public:
friend class Singleton;
void print(){cout<<"Dotted";}
private:
Dotted(){};
};
| There are several problems with your code:
You mean to return type Singleton& or const Singleton&. You are currently returning by value, which is attempting to invoke a copy constructor, and no such constructor exists.
Your default constructor in Dotted probably is not available in Singleton. I suggest you make Singleton a friend of Dotted so that it is able to access that constructor. Although not 100% sure on this one.
You forgot to make the function print() virtual, so your override won't manifest itself.
You have put "friend" in the wrong place; you need to declare Singleton a friend of Dotted in Dotted, not within Singleton.
You should not make your definition of Singleton::instant inline as it needs to construct an instance of Dotted and, in order to do that, it needs to see Dotted's definition. So you should move that to a source file where it is able to see both Dotted and Singleton's complete definitions, respectively.
You need to put Singleton* Singleton::instance_ = 0; in a source file somewhere.
You are missing an else clause in your if(!style) section; currently, if the STYLE environment variable is set, but isn't set to "dotted", then you end up returning a null singleton.
In addition to the above, I strongly advise you to avoid environment variables and singletons. Both of them are examples of "shared mutable state" and can lead to a whole lot of messiness. Singletons, though they have appeared in "design pattern" books for quite some time, are now being understood to be design anti-patterns. It is a much more flexible approach to have an interface that you pass around and simply happen to instantiate once rather than bake in the fact that it exists once into its API.
For example, for your particular case, I would suggest something like the following:
class Printer
{
public:
virtual ~Printer(){}
virtual void print()const = 0
};
class StringPrinter : public Printer
{
public:
StringPrinter() : _str("") {}
StringPrinter(const std::string& str) : _str(str) {}
StringPrinter(const StringPrinter& o) : _str(o._str) {}
virtual ~StringPrinter(){}
virtual void print()const{ std::cout << _str << std::endl; }
StringPrinter& operator=(const StringPrinter& o){ _str = o._str; return *this;}
private:
std::string _str;
};
Then, in any class where you previously used Singleton, simply take a const Printer& object. And print to that object. Elsewhere, you can conditionally construct a StringPrinter("Singleton") or StringPrinter("dotted"). Or possibly some other instance of that interface, although I would suggest using QSettings or some sort of configuration file in place of environment variables, or at least use MYAPPLICATIONNAME_STYLE instead of just STYLE; in other words, if you are going to go the environment variable route, at least qualify its name.
|
2,797,451 | 2,797,537 | GDI+ not clearing my window on repaint for vista | on WM_PAINT i do the following:
//RectF mNameRect;
//WCHAR* mName;
//HWND mWin; // this is the window handle
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(mWin, &ps);
Graphics g(hdc);
g.Clear(Color::White);
StringFormat stringForm;
stringForm.SetLineAlignment(StringAlignmentCenter);
stringForm.SetAlignment(StringAlignmentCenter);
// set the rectangle to the size of the whole window
mNameRect.Width = static_cast<float>(size.cx);
mNameRect.Height = static_cast<float>(size.cy);
g.DrawString(mName, -1, &mNameFont, mNameRect, &stringForm, &mNameBrush);
EndPaint(mWin, &ps);
}
In XP this works fine, the mName is displayed in the middle of the window. However on Vista the text doesn't move, it stays in its location no matter how I resize the window. the g.Clear(Color::White) doesn't seem to do any difference. The text doesn't even change position when the window is hidden behind another window and on focus needs to be repainted again.
How do I make mName change position in Vista?
Edit:
The paint code gets called via WM_PAINT and via WM_SIZE in the following manner:
// WndProc function
switch (msg){
case WM_SIZE:
// intentionally call paint when WM_SIZE is triggered
case WM_PAINT:
paint();
break;
| You are explicitly calling your paint() function when the window is resized. However, your window is not invalidated, so it could be that the system is restricting your painting efforts to the region marked "dirty".
Instead of calling paint() directly, it is better to use InvalidateRgn to trigger a repaint. This will cause a WM_PAINT to be sent which will be handled by your application in the normal way. As a bonus, you can also tell InvalidateRgn to erase the background for you
InvalidateRgn(hWnd, NULL, TRUE);
|
2,797,468 | 2,797,482 | capture the last WM_SIZE | When I resize my window I want to tell another part of my program that my window has changed size. I read on MSDN that:
WM SIZE Message
The WM SIZE message is sent to a window after its size has changed.
However, I receive the WM_SIZE even when dragging.
I noticed that there is also a WM_SIZING message that is sent when my window is resizing. At the moment I do not see the difference between WM_SIZE and WM_SIZING.
Is there some way I can capture the very last WM_SIZE message, as to not "spam" my program with resize messages?
| When you start dragging a window, the system enters a modal move/resize loop; it does not return to your own message loop until the drag action has finished. You are still getting WM_SIZE because it is sent directly to the window procedure, but it does not flow through your own message loop.
At the beginning of such a modal drag action, the system sends WM_ENTERSIZEMOVE to your window procedure. When you release the mouse button, your application will get WM_EXITSIZEMOVE. That is probably the message you want to trigger on.
|
2,797,533 | 2,797,727 | Undefined template methods trick? | A colleague of mine told me about a little piece of design he has used with his team that sent my mind boiling. It's a kind of traits class that they can specialize in an extremely decoupled way.
I've had a hard time understanding how it could possibly work, and I am still unsure of the idea I have, so I thought I would ask for help here.
We are talking g++ here, specifically the versions 3.4.2 and 4.3.2 (it seems to work with both).
The idea is quite simple:
1- Define the interface
// interface.h
template <class T>
struct Interface
{
void foo(); // the method is not implemented, it could not work if it was
};
//
// I do not think it is necessary
// but they prefer free-standing methods with templates
// because of the automatic argument deduction
//
template <class T>
void foo(Interface<T>& interface) { interface.foo(); }
2- Define a class, and in the source file specialize the interface for this class (defining its methods)
// special.h
class Special {};
// special.cpp
#include "interface.h"
#include "special.h"
//
// Note that this specialization is not visible outside of this translation unit
//
template <>
struct Interface<Special>
{
void foo() { std::cout << "Special" << std::endl; }
};
3- To use, it's simple too:
// main.cpp
#include "interface.h"
class Special; // yes, it only costs a forward declaration
// which helps much in term of dependencies
int main(int argc, char* argv[])
{
Interface<Special> special;
foo(special);
return 0;
};
It's an undefined symbol if no translation unit defined a specialization of Interface for Special.
Now, I would have thought this would require the export keyword, which to my knowledge has never been implemented in g++ (and only implemented once in a C++ compiler, with its authors advising anyone not to, given the time and effort it took them).
I suspect it's got something to do with the linker resolving the templates methods...
Do you have ever met anything like this before ?
Does it conform to the standard or do you think it's a fortunate coincidence it works ?
I must admit I am quite puzzled by the construct...
| Like @Steward suspected, it's not valid. Formally it's effectively causing undefined behavior, because the Standard rules that for a violation no diagnostic is required, which means the implementation can silently do anything it wants. At 14.7.3/6
If a template, a member template or the member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.
In practice at least on GCC, it's implicitly instantiating the primary template Interface<T> since the specialization wasn't declared and is not visible in main, and then calling Interface<T>::foo. If its definition is visible, it instatiates the primary definition of the member function (which is why when it is defined, it wouldn't work).
Instantiated function name symbols have weak linkage because they could possibly be present multiple times in different object files, and have to be merged into one symbol in the final program. Contrary, members of explicit specializations that aren't templates anymore have strong linkage so they will dominate weak linkage symbols and make the call end up in the specialization. All this is implementation detail, and the Standard has no such notion of weak/strong linkage. You have to declare the specialization prior to creating the special object:
template <>
struct Interface<Special>;
The Standard lays it bare (emphasize by me)
The placement of explicit specialization declarations for function templates, class templates, member functions of class templates, static data members of class templates, member classes of class templates, member class templates of class templates, member function templates of class templates, member functions of member templates of class templates, member functions of member templates of non-template classes, member function templates of member classes of class templates, etc., and the placement of partial specialization declarations of class templates, member class templates of non-template classes, member class templates of class templates, etc., can affect whether a program is well-formed according to the relative positioning of the explicit specialization declarations and their points of instantiation in the translation unit as specified above and below. When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.
|
2,797,538 | 2,797,555 | question about ? and : in c++ | Why this statement :
int a = 7, b = 8, c = 0;
c = b>a?a>b?a++:b++:a++?b++:a--;
cout << c;
is not equal to :
int a = 7, b = 8, c = 0;
c = (b>a?(a>b?a++:b++):a++)?b++:a--;
cout << c;
and is equal to :
int a = 7, b = 8, c = 0;
c = b>a?(a>b?a++:b++):(a++?b++:a--);
cout << c;
Please give me some reason. Why ?
| Because ? : is right-to-left associative. It's defined like that in the language.
|
2,797,813 | 2,797,823 | How to convert a command-line argument to int? | I need to get an argument and convert it to an int. Here is my code so far:
#include <iostream>
using namespace std;
int main(int argc,int argvx[]) {
int i=1;
int answer = 23;
int temp;
// decode arguments
if(argc < 2) {
printf("You must provide at least one argument\n");
exit(0);
}
// Convert it to an int here
}
| Since this answer was somehow accepted and thus will appear at the top, although it's not the best, I've improved it based on the other answers and the comments.
The C way; simplest, but will treat any invalid number as 0:
#include <cstdlib>
int x = atoi(argv[1]);
The C way with input checking:
#include <cstdlib>
errno = 0;
char *endptr;
long int x = strtol(argv[1], &endptr, 10);
if (endptr == argv[1]) {
std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (*endptr) {
std::cerr << "Trailing characters after number: " << argv[1] << '\n';
} else if (errno == ERANGE) {
std::cerr << "Number out of range: " << argv[1] << '\n';
}
The C++ iostreams way with input checking:
#include <sstream>
std::istringstream ss(argv[1]);
int x;
if (!(ss >> x)) {
std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (!ss.eof()) {
std::cerr << "Trailing characters after number: " << argv[1] << '\n';
}
Alternative C++ way since C++11:
#include <stdexcept>
#include <string>
std::string arg = argv[1];
try {
std::size_t pos;
int x = std::stoi(arg, &pos);
if (pos < arg.size()) {
std::cerr << "Trailing characters after number: " << arg << '\n';
}
} catch (std::invalid_argument const &ex) {
std::cerr << "Invalid number: " << arg << '\n';
} catch (std::out_of_range const &ex) {
std::cerr << "Number out of range: " << arg << '\n';
}
All four variants assume that argc >= 2. All accept leading whitespace; check isspace(argv[1][0]) if you don't want that. All except atoi reject trailing whitespace.
|
2,798,071 | 3,802,332 | Pure/const functions in C++ | I'm thinking of using pure/const functions more heavily in my C++ code. (pure/const attribute in GCC)
However, I am curious how strict I should be about it and what could possibly break.
The most obvious case are debug outputs (in whatever form, could be on cout, in some file or in some custom debug class). I probably will have a lot of functions, which don't have any side effects despite this sort of debug output. No matter if the debug output is made or not, this will absolutely have no effect on the rest of my application.
Or another case I'm thinking of is the use of some SmartPointer class which may do some extra stuff in global memory when being in debug mode. If I use such an object in a pure/const function, it does have some slight side effects (in the sense that some memory probably will be different) which should not have any real side effects though (in the sense that the behaviour is in any way different).
Similar also for mutexes and other stuff. I can think of many complex cases where it has some side effects (in the sense of that some memory will be different, maybe even some threads are created, some filesystem manipulation is made, etc) but has no computational difference (all those side effects could very well be left out and I would even prefer that).
So, to summarize, I want to mark functions as pure/const which are not pure/const in a strict sense. An easy example:
int foo(int) __attribute__((const));
int bar(int x) {
int sum = 0;
for(int i = 0; i < 100; ++i)
sum += foo(x);
return sum;
}
int foo_callcounter = 0;
int main() {
cout << "bar 42 = " << bar(42) << endl;
cout << "foo callcounter = " << foo_callcounter << endl;
}
int foo(int x) {
cout << "DEBUG: foo(" << x << ")" << endl;
foo_callcounter++;
return x; // or whatever
}
Note that the function foo is not const in a strict sense. Though, it doesn't matter what foo_callcounter is in the end. It also doesn't matter if the debug statement is not made (in case the function is not called).
I would expect the output:
DEBUG: foo(42)
bar 42 = 4200
foo callcounter = 1
And without optimisation:
DEBUG: foo(42) (100 times)
bar 42 = 4200
foo callcounter = 100
Both cases are totally fine because what only matters for my usecase is the return value of bar(42).
How does it work out in practice? If I mark such functions as pure/const, could it break anything (considering that the code is all correct)?
Note that I know that some compilers might not support this attribute at all. (BTW., I am collecting them here.) I also know how to make use of thes attributes in a way that the code stays portable (via #defines). Also, all compilers which are interesting to me support it in some way; so I don't care about if my code runs slower with compilers which do not.
I also know that the optimised code probably will look different depending on the compiler and even the compiler version.
Very relevant is also this LWN article "Implications of pure and constant functions", especially the "Cheats" chapter. (Thanks ArtemGr for the hint.)
|
I would expect the output:
I would expect the input:
int bar(int x) {
return foo(x) * 100;
}
Your code actually looks strange for me. As a maintainer I would think that either foo actually has side effects or more likely rewrite it immediately to the above function.
How does it work out in practice? If I mark such functions as pure/const, could it break anything (considering that the code is all correct)?
If the code is all correct then no. But the chances that your code is correct are small. If your code is incorrect then this feature can mask out bugs:
int foo(int x) {
globalmutex.lock();
// complicated calculation code
return -1;
// more complicated calculation
globalmutex.unlock();
return x;
}
Now given the bar from above:
int main() {
cout << bar(-1);
}
This terminates with __attribute__((const)) but deadlocks otherwise.
It also highly depends on the implementation. For example:
void f() {
for(;;)
{
globalmutex.unlock();
cout << foo(42) << '\n';
globalmutex.lock();
}
}
Where the compiler should move the call foo(42)? Is it allowed to optimize this code? Not in general! So unless the loop is really trivial you have no benefits of your feature. But if your loop is trivial you can easily optimize it yourself.
EDIT: as Albert requested a less obvious situation, here it comes:
F
or example if you implement operator << for an ostream, you use the ostream::sentry which locks the stream buffer. Suppose you call pure/const f after you released or before you locked it. Someone uses this operator cout << YourType() and f also uses cout << "debug info". According to you the compiler is free to put the invocation of f into the critical section. Deadlock occurs.
|
2,798,188 | 2,798,511 | pure/const function attributes in different compilers | pure is a function attribute which says that a function does not modify any global memory.
const is a function attribute which says that a function does not read/modify any global memory.
Given that information, the compiler can do some additional optimisations.
Example for GCC:
float sigmoid(float x) __attribute__ ((const));
float calculate(float x, unsigned int C) {
float sum = 0;
for(unsigned int i = 0; i < C; ++i)
sum += sigmoid(x);
return sum;
}
float sigmoid(float x) { return 1.0f / (1.0f - exp(-x)); }
In that example, the compiler could optimise the function calculate to:
float calculate(float x, unsigned int C) {
float sum = 0;
float temp = C ? sigmoid(x) : 0.0f;
for(unsigned int i = 0; i < C; ++i)
sum += temp;
return sum;
}
Or if your compiler is clever enough (and not so strict about floats):
float calculate(float x, unsigned int C) { return C ? sigmoid(x) * C : 0.0f; }
How can I mark a function in such way for the different compilers, i.e. GCC, Clang, ICC, MSVC or others?
|
GCC: pure/const function attributes
llvm-gcc: supports the GCC pure/const attributes
Clang: seems to support it (I tried on a simple example with the GCC style attributes and it worked.)
ICC: seems to adopt the GCC attributes (Sorry, only a forum post.)
MSVC: Seems not to support it. (discussion)
In general, it seems that almost all compilers support the GCC attributes. MSVC is so far the only compiler which does not support them (and which also doesn't have any alternative).
|
2,798,236 | 2,798,244 | template; operator (int) | regarding my Point struct already mentioned here:
template class: ctor against function -> new C++ standard
is there a chance to replace the function toint() with a cast-operator (int)?
namespace point {
template < unsigned int dims, typename T >
struct Point {
T X[ dims ];
//umm???
template < typename U >
Point< dims, U > operator U() const {
Point< dims, U > ret;
std::copy( X, X + dims, ret.X );
return ret;
}
//umm???
Point< dims, int > operator int() const {
Point<dims, int> ret;
std::copy( X, X + dims, ret.X );
return ret;
}
//OK
Point<dims, int> toint() {
Point<dims, int> ret;
std::copy( X, X + dims, ret.X );
return ret;
}
}; //struct Point
template < typename T >
Point< 2, T > Create( T X0, T X1 ) {
Point< 2, T > ret;
ret.X[ 0 ] = X0; ret.X[ 1 ] = X1;
return ret;
}
}; //namespace point
int main(void) {
using namespace point;
Point< 2, double > p2d = point::Create( 12.3, 34.5 );
Point< 2, int > p2i = (int)p2d; //äähhm???
std::cout << p2d.str() << std::endl;
char c; std::cin >> c;
return 0;
}
I think the problem is here that C++ cannot distinguish between different return types? many thanks in advance.
regards
Oops
| The correct syntax is
operator int() const {
...
There's no need to have that extra return type when you overload the cast operator.
And when you say (int)x, the compiler really expects to get an int, not a Point<dims, int>. Probably you want a constructor instead.
template <typename U>
Point(const Point<dims, U>& other) { ... }
|
2,798,322 | 2,839,320 | How to overlay direct3d in directshow | I am looking for a tutorial or documentation on how to overlay direct3d on top of a video (webcam) feed in directshow.
I want to provide a virtual web cam (a virtual device that looks like a web cam to the system (ie. so that it be used where ever a normal webcam could be used like IM video chats)
I want to capture a video feed from a webcam attached to the computer.
I want to overlay a 3d model on top of the video feed and provide that as the output.
I had planned on doing this in directshow only because it looked possible to do this in it. If you have any ideas about possible alternatives, I am all ears.
I am writing c++ using visual studio 2008.
| Use the Video Mixing Renderer Filter to render the video to a texture, then render it to the scene as a full screen quad. After that you can render the rest of the 3D stuff on top and then present the scene.
|
2,798,608 | 2,798,624 | C++: Declare a global class and access it from other classes? | I have a class which should be declared globally from main() and accessed from other declared classes in the program, how do I do that?
class A{
int i;
int value(){ return i;}
};
class B{
global A a; //or extern??
int calc(){
return a.value()+10;
}
}
main(){
global A a;
B b;
cout<<b.calc();
}
| You probably really do not want to do this, but if you must - in the file that contains main:
#include "A.h"
A a;
int main() {
...
}
and then in the files that need to access the global:
#include "A.h"
extern A a;
You will need to put the declaration of A in the A.h header file in order for this to work.
|
2,798,644 | 2,798,652 | Selecting size of vector of vectors | I have a class called Grid that declares a vector of vectors like this:
typedef vector<int> row;
typedef vector<row> myMatrix;
myMatrix sudoku_;
The constructor looks like this:
grid::grid() : sudoku_(9,9)
{
}
As you can see, the constructor is initializing it to be a 9x9 grid. How can I make it work so that the user is asked for a number, say n, and the grid is initialized n x n ?
| vector has a constructor that allows you to initialize it to a certain size with copies of a given value:
grid::grid(size_t w, size_t h) : sudoku_(w, row(h)) {}
|
2,798,708 | 2,798,767 | Difference between C++ Keyboard keycode and JAVA KeyEvent keycode | I noticed a difference between the keycodes that vkCode in C++ gives and the ones that Java's KeyEvent gives us. (Ofcourse the normal characters have the same code (0 => 48 just like the ASCII) but they differ in the other keys).
Is there a way to 'translate' them from one to the other (What's the logic behind each one?) or am I supposed to use loads of switches and IFs for that.
If it helps, my app is half in C++ and half in JAVA because of the Native Hooks that c++ gives us and it gets the keycodes of the keys that the user presses and then the java is going to use them.
Thanks in advance.
|
or am I supposed to use loads of switches and IFs
You can probably just put them in a lookup table, that is, put the Java KeyCodes in a large array, so you just need to do javaKeyCode = keyLut[cppScanCode].
One list of scan codes can be found here, and the VK_KEYCODES can of course be found in the API docs for KeyEvent.
Java is designed to be platform independent, so pressing the left-key for instance, will always yield a VK_LEFT, no matter scan code. I'm not entirely sure, but I suppose the C++-scancode is hardware dependent.
|
2,798,832 | 2,799,346 | QApplication In Non-Main Thread | I need to exec() a QApplication in a thread that is not main (my GUIs must be plugins that can be dynamically loaded and unloaded at runtime, so I have no access to the main thread). Does anyone know of a (relatively) painless way to hack around Qt's restriction against starting QApplication outside of main?
I'm developing in Linux with Qt4 in C++ using gcc4.3.4.
| If you are using QThread then you already have normal Qt event loop and can just run exec() inside QThread::run() function. While you can't work with GUI objects outside of the main thread you still can interact with them through queued signal/slot connections. Maybe you can try to store pointer to the main thread QThread object and call QObject::moveToThread() to move your GUI objects to the main thread instead of moving QApplication into another thread.
I think it's not really good idea to try to go against toolkit with different kind of hacks and kluges.
|
2,798,959 | 2,798,987 | It is good programming practice to always check for null pointers before using an object in C++? | This seems like a lot of work; to check for null each time an object is used.
I have been advised that it is a good idea to check for null pointers so you don't have to spend time looking for where segmentation faults occur.
Just wondering what the community here thinks?
| Use references whenever you can, because they can't be null, therefore you don't have to check if they are null.
It's good practice to check for null in function parameters and other places you may be dealing with pointers someone else is passing you. However, in your own code, you might have pointers you know will always be pointing to a valid object, so a null check is probably overkill... just use your common sense.
I don't know if it really helps with debugging because any debugger will be showing you pretty clearly that a null pointer was used and it won't take long to find it. It's more about making sure you don't crash if another programmer passes in NULL, or that the mistake is picked up by an assert in a debug build.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.