Search Results

Search found 3389 results on 136 pages for 'const'.

Page 13/136 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • How do I use D3DXVec3Unproject with D3D11?

    - by Miguel P
    I'm having a small issue with D3DXVec3Unproject. I'm currently using Direct3D 11 and not 10, and the signature for this function is: D3DXVECTOR3 *pOut, CONST D3DXVECTOR3 *pV, CONST D3D10_VIEWPORT *pViewport, CONST D3DXMATRIX *pProjection, CONST D3DXMATRIX *pView, CONST D3DXMATRIX *pWorld As you may have noticed, it requires a D3D10_VIEWPORT, and I'm using a Direct3D 11 viewport, D3D11_VIEWPORT. Do you have any ideas how I can use D3DXVec3Unproject with Direct3D 11?

    Read the article

  • Is this a pattern? Should it be?

    - by Arkadiy
    The following is more of a statement than a question - it describes something that may be a pattern. The question is: is this a known pattern? Or, if it's not, should it be? I've had a situation where I had to iterate over two dissimilar multi-layer data structures and copy information from one to the other. Depending on particular use case, I had around eight different kinds of layers, combined in about eight different combinations: A-B-C B-C A-C D-E A-D-E and so on After a few unsuccessful attempts to factor out the repetition of per-layer iteration code, I realized that the key difficulty in this refactoring was the fact that the bottom level needed access to data gathered at higher levels. To explicitly accommodate this requirement, I introduced IterationContext class with a number of get() and set() methods for accumulating the necessary information. In the end, I had the following class structure: class Iterator { virtual void iterateOver(const Structure &dataStructure1, IterationContext &ctx) const = 0; }; class RecursingIterator : public Iterator { RecursingIterator(const Iterator &below); }; class IterateOverA : public RecursingIterator { virtual void iterateOver(const Structure &dataStructure1, IterationContext &ctx) const { // Iterate over members in dataStructure1 // locate corresponding item in dataStructure2 (passed via context) // and set it in the context // invoke the sub-iterator }; class IterateOverB : public RecursingIterator { virtual void iterateOver(const Structure &dataStructure1, IterationContext &ctx) const { // iterate over members dataStructure2 (form context) // set dataStructure2's item in the context // locate corresponding item in dataStructure2 (passed via context) // invoke the sub-iterator }; void main() { class FinalCopy : public Iterator { virtual void iterateOver(const Structure &dataStructure1, IterationContext &ctx) const { // copy data from structure 1 to structure 2 in the context, // using some data from higher levels as needed } } IterationContext ctx(dateStructure2); IterateOverA(IterateOverB(FinalCopy())).iterate(dataStructure1, ctx); } It so happens that dataStructure1 is a uniform data structure, similar to XML DOM in that respect, while dataStructure2 is a legacy data structure made of various structs and arrays. This allows me to pass dataStructure1 outside of the context for convenience. In general, either side of the iteration or both sides may be passed via context, as convenient. The key situation points are: complicated code that needs to be invoked in "layers", with multiple combinations of layer types possible at the bottom layer, the information from top layers needs to be visible. The key implementation points are: use of context class to access the data from all levels of iteration complicated iteration code encapsulated in implementation of pure virtual function two interfaces - one aware of underlying iterator, one not aware of it. use of const & to simplify the usage syntax.

    Read the article

  • help understanding differences between #define, const and enum in C and C++ on assembly level.

    - by martin
    recently, i am looking into assembly codes for #define, const and enum: C codes(#define): 3 #define pi 3 4 int main(void) 5 { 6 int a,r=1; 7 a=2*pi*r; 8 return 0; 9 } assembly codes(for line 6 and 7 in c codes) generated by GCC: 6 mov $0x1, -0x4(%ebp) 7 mov -0x4(%ebp), %edx 7 mov %edx, %eax 7 add %eax, %eax 7 add %edx, %eax 7 add %eax, %eax 7 mov %eax, -0x8(%ebp) C codes(enum): 2 int main(void) 3 { 4 int a,r=1; 5 enum{pi=3}; 6 a=2*pi*r; 7 return 0; 8 } assembly codes(for line 4 and 6 in c codes) generated by GCC: 6 mov $0x1, -0x4(%ebp) 7 mov -0x4(%ebp), %edx 7 mov %edx, %eax 7 add %eax, %eax 7 add %edx, %eax 7 add %eax, %eax 7 mov %eax, -0x8(%ebp) C codes(const): 4 int main(void) 5 { 6 int a,r=1; 7 const int pi=3; 8 a=2*pi*r; 9 return 0; 10 } assembly codes(for line 7 and 8 in c codes) generated by GCC: 6 movl $0x3, -0x8(%ebp) 7 movl $0x3, -0x4(%ebp) 8 mov -0x4(%ebp), %eax 8 add %eax, %eax 8 imul -0x8(%ebp), %eax 8 mov %eax, 0xc(%ebp) i found that use #define and enum, the assembly codes are the same. The compiler use 3 add instructions to perform multiplication. However, when use const, imul instruction is used. Anyone knows the reason behind that?

    Read the article

  • What does it mean to pass a &variable to a function? E.g., string& insert ( size_t pos1, const strin

    - by Bob Montgomery
    I understand passing a pointer, and returning a pointer: char * strcat ( char * destination, const char * source ); You're passing a variable that contains the address to a char; returning the same. But what does it mean to pass something using the reference operator? Or to return it? string& insert ( size_t pos1, const string& str ); I mean, I understand what actually happens, I just don't understand the notation. Why isn't the notation this instead: string * insert ( size_t pos1, const string * str ); //made up I presume it has something to do with passing/returning the instance of a class, but what? Is this syntax valid; if not why not and if so what does it mean? char & strcat ( char & destination, const char & source ); //made up (all of the function declarations, except the last made-up two, are from http://www.cplusplus.com )

    Read the article

  • How to maintain encapsulation with composition in C++?

    - by iFreilicht
    I am designing a class Master that is composed from multiple other classes, A, Base, C and D. These four classes have absolutely no use outside of Master and are meant to split up its functionality into manageable and logically divided packages. They also provide extensible functionality as in the case of Base, which can be inherited from by clients. But, how do I maintain encapsulation of Master with this design? So far, I've got two approaches, which are both far from perfect: 1. Replicate all accessors: Just write accessor-methods for all accessor-methods of all classes that Master is composed of. This leads to perfect encapsulation, because no implementation detail of Master is visible, but is extremely tedious and makes the class definition monstrous, which is exactly what the composition should prevent. Also, adding functionality to one of the composees (is that even a word?) would require to re-write all those methods in Master. An additional problem is that inheritors of Base could only alter, but not add functionality. 2. Use non-assignable, non-copyable member-accessors: Having a class accessor<T> that can not be copied, moved or assigned to, but overrides the operator-> to access an underlying shared_ptr, so that calls like Master->A()->niceFunction(); are made possible. My problem with this is that it kind of breaks encapsulation as I would now be unable to change my implementation of Master to use a different class for the functionality of niceFunction(). Still, it is the closest I've gotten without using the ugly first approach. It also fixes the inheritance issue quite nicely. A small side question would be if such a class already existed in std or boost. EDIT: Wall of code I will now post the code of the header files of the classes discussed. It may be a bit hard to understand, but I'll give my best in explaining all of it. 1. GameTree.h The foundation of it all. This basically is a doubly-linked tree, holding GameObject-instances, which we'll later get to. It also has it's own custom iterator GTIterator, but I left that out for brevity. WResult is an enum with the values SUCCESS and FAILED, but it's not really important. class GameTree { public: //Static methods for the root. Only one root is allowed to exist at a time! static void ConstructRoot(seed_type seed, unsigned int depth); inline static bool rootExists(){ return static_cast<bool>(rootObject_); } inline static weak_ptr<GameTree> root(){ return rootObject_; } //delta is in ms, this is used for velocity, collision and such void tick(unsigned int delta); //Interaction with the tree inline weak_ptr<GameTree> parent() const { return parent_; } inline unsigned int numChildren() const{ return static_cast<unsigned int>(children_.size()); } weak_ptr<GameTree> getChild(unsigned int index) const; template<typename GOType> weak_ptr<GameTree> addChild(seed_type seed, unsigned int depth = 9001){ GOType object{ new GOType(seed) }; return addChildObject(unique_ptr<GameTree>(new GameTree(std::move(object), depth))); } WResult moveTo(weak_ptr<GameTree> newParent); WResult erase(); //Iterators for for( : ) loop GTIterator& begin(){ return *(beginIter_ = std::move(make_unique<GTIterator>(children_.begin()))); } GTIterator& end(){ return *(endIter_ = std::move(make_unique<GTIterator>(children_.end()))); } //unloading should be used when objects are far away WResult unloadChildren(unsigned int newDepth = 0); WResult loadChildren(unsigned int newDepth = 1); inline const RenderObject& renderObject() const{ return gameObject_->renderObject(); } //Getter for the underlying GameObject (I have not tested the template version) weak_ptr<GameObject> gameObject(){ return gameObject_; } template<typename GOType> weak_ptr<GOType> gameObject(){ return dynamic_cast<weak_ptr<GOType>>(gameObject_); } weak_ptr<PhysicsObject> physicsObject() { return gameObject_->physicsObject(); } private: GameTree(const GameTree&); //copying is only allowed internally GameTree(shared_ptr<GameObject> object, unsigned int depth = 9001); //pointer to root static shared_ptr<GameTree> rootObject_; //internal management of a child weak_ptr<GameTree> addChildObject(shared_ptr<GameTree>); WResult removeChild(unsigned int index); //private members shared_ptr<GameObject> gameObject_; shared_ptr<GTIterator> beginIter_; shared_ptr<GTIterator> endIter_; //tree stuff vector<shared_ptr<GameTree>> children_; weak_ptr<GameTree> parent_; unsigned int selfIndex_; //used for deletion, this isn't necessary void initChildren(unsigned int depth); //constructs children }; 2. GameObject.h This is a bit hard to grasp, but GameObject basically works like this: When constructing a GameObject, you construct its basic attributes and a CResult-instance, which contains a vector<unique_ptr<Construction>>. The Construction-struct contains all information that is needed to construct a GameObject, which is a seed and a function-object that is applied at construction by a factory. This enables dynamic loading and unloading of GameObjects as done by GameTree. It also means that you have to define that factory if you inherit GameObject. This inheritance is also the reason why GameTree has a template-function gameObject<GOType>. GameObject can contain a RenderObject and a PhysicsObject, which we'll later get to. Anyway, here's the code. class GameObject; typedef unsigned long seed_type; //this declaration magic means that all GameObjectFactorys inherit from GameObjectFactory<GameObject> template<typename GOType> struct GameObjectFactory; template<> struct GameObjectFactory<GameObject>{ virtual unique_ptr<GameObject> construct(seed_type seed) const = 0; }; template<typename GOType> struct GameObjectFactory : GameObjectFactory<GameObject>{ GameObjectFactory() : GameObjectFactory<GameObject>(){} unique_ptr<GameObject> construct(seed_type seed) const{ return unique_ptr<GOType>(new GOType(seed)); } }; //same as with the factories. this is important for storing them in vectors template<typename GOType> struct Construction; template<> struct Construction<GameObject>{ virtual unique_ptr<GameObject> construct() const = 0; }; template<typename GOType> struct Construction : Construction<GameObject>{ Construction(seed_type seed, function<void(GOType*)> func = [](GOType* null){}) : Construction<GameObject>(), seed_(seed), func_(func) {} unique_ptr<GameObject> construct() const{ unique_ptr<GameObject> gameObject{ GOType::factory.construct(seed_) }; func_(dynamic_cast<GOType*>(gameObject.get())); return std::move(gameObject); } seed_type seed_; function<void(GOType*)> func_; }; typedef struct CResult { CResult() : constructions{} {} CResult(CResult && o) : constructions(std::move(o.constructions)) {} CResult& operator= (CResult& other){ if (this != &other){ for (unique_ptr<Construction<GameObject>>& child : other.constructions){ constructions.push_back(std::move(child)); } } return *this; } template<typename GOType> void push_back(seed_type seed, function<void(GOType*)> func = [](GOType* null){}){ constructions.push_back(make_unique<Construction<GOType>>(seed, func)); } vector<unique_ptr<Construction<GameObject>>> constructions; } CResult; //finally, the GameObject class GameObject { public: GameObject(seed_type seed); GameObject(const GameObject&); virtual void tick(unsigned int delta); inline Matrix4f trafoMatrix(){ return physicsObject_->transformationMatrix(); } //getter inline seed_type seed() const{ return seed_; } inline CResult& properties(){ return properties_; } inline const RenderObject& renderObject() const{ return *renderObject_; } inline weak_ptr<PhysicsObject> physicsObject() { return physicsObject_; } protected: virtual CResult construct_(seed_type seed) = 0; CResult properties_; shared_ptr<RenderObject> renderObject_; shared_ptr<PhysicsObject> physicsObject_; seed_type seed_; }; 3. PhysicsObject That's a bit easier. It is responsible for position, velocity and acceleration. It will also handle collisions in the future. It contains three Transformation objects, two of which are optional. I'm not going to include the accessors on the PhysicsObject class because I tried my first approach on it and it's just pure madness (way over 30 functions). Also missing: the named constructors that construct PhysicsObjects with different behaviour. class Transformation{ Vector3f translation_; Vector3f rotation_; Vector3f scaling_; public: Transformation() : translation_{ 0, 0, 0 }, rotation_{ 0, 0, 0 }, scaling_{ 1, 1, 1 } {}; Transformation(Vector3f translation, Vector3f rotation, Vector3f scaling); inline Vector3f translation(){ return translation_; } inline void translation(float x, float y, float z){ translation(Vector3f(x, y, z)); } inline void translation(Vector3f newTranslation){ translation_ = newTranslation; } inline void translate(float x, float y, float z){ translate(Vector3f(x, y, z)); } inline void translate(Vector3f summand){ translation_ += summand; } inline Vector3f rotation(){ return rotation_; } inline void rotation(float pitch, float yaw, float roll){ rotation(Vector3f(pitch, yaw, roll)); } inline void rotation(Vector3f newRotation){ rotation_ = newRotation; } inline void rotate(float pitch, float yaw, float roll){ rotate(Vector3f(pitch, yaw, roll)); } inline void rotate(Vector3f summand){ rotation_ += summand; } inline Vector3f scaling(){ return scaling_; } inline void scaling(float x, float y, float z){ scaling(Vector3f(x, y, z)); } inline void scaling(Vector3f newScaling){ scaling_ = newScaling; } inline void scale(float x, float y, float z){ scale(Vector3f(x, y, z)); } void scale(Vector3f factor){ scaling_(0) *= factor(0); scaling_(1) *= factor(1); scaling_(2) *= factor(2); } Matrix4f matrix(){ return WMatrix::Translation(translation_) * WMatrix::Rotation(rotation_) * WMatrix::Scale(scaling_); } }; class PhysicsObject; typedef void tickFunction(PhysicsObject& self, unsigned int delta); class PhysicsObject{ PhysicsObject(const Transformation& trafo) : transformation_(trafo), transformationVelocity_(nullptr), transformationAcceleration_(nullptr), tick_(nullptr) {} PhysicsObject(PhysicsObject&& other) : transformation_(other.transformation_), transformationVelocity_(std::move(other.transformationVelocity_)), transformationAcceleration_(std::move(other.transformationAcceleration_)), tick_(other.tick_) {} Transformation transformation_; unique_ptr<Transformation> transformationVelocity_; unique_ptr<Transformation> transformationAcceleration_; tickFunction* tick_; public: void tick(unsigned int delta){ tick_ ? tick_(*this, delta) : 0; } inline Matrix4f transformationMatrix(){ return transformation_.matrix(); } } 4. RenderObject RenderObject is a base class for different types of things that could be rendered, i.e. Meshes, Light Sources or Sprites. DISCLAIMER: I did not write this code, I'm working on this project with someone else. class RenderObject { public: RenderObject(float renderDistance); virtual ~RenderObject(); float renderDistance() const { return renderDistance_; } void setRenderDistance(float rD) { renderDistance_ = rD; } protected: float renderDistance_; }; struct NullRenderObject : public RenderObject{ NullRenderObject() : RenderObject(0.f){}; }; class Light : public RenderObject{ public: Light() : RenderObject(30.f){}; }; class Mesh : public RenderObject{ public: Mesh(unsigned int seed) : RenderObject(20.f) { meshID_ = 0; textureID_ = 0; if (seed == 1) meshID_ = Model::getMeshID("EM-208_heavy"); else meshID_ = Model::getMeshID("cube"); }; unsigned int getMeshID() const { return meshID_; } unsigned int getTextureID() const { return textureID_; } private: unsigned int meshID_; unsigned int textureID_; }; I guess this shows my issue quite nicely: You see a few accessors in GameObject which return weak_ptrs to access members of members, but that is not really what I want. Also please keep in mind that this is NOT, by any means, finished or production code! It is merely a prototype and there may be inconsistencies, unnecessary public parts of classes and such.

    Read the article

  • Error compiling / linking e text editor on Linux

    - by jckdnk111
    The code compiles without too much complaint, but the last step fails with the error below. There is some discussion about it on the e forum, but still no answer. [LD] e ../external/out.release/lib/libpcre.a(pcre_tables.o):(.rodata+0x0): multiple definition of `_pcre_OP_lengths' .objs.release/cx_pcre_tables.o:(.rodata+0x0): first defined here ../external/out.release/lib/libpcre.a(pcre_tables.o):(.rodata+0x70): multiple definition of `_pcre_utf8_table1' .objs.release/cx_pcre_tables.o:(.rodata+0x70): first defined here ../external/out.release/lib/libpcre.a(pcre_tables.o):(.rodata+0x88): multiple definition of `_pcre_utf8_table1_size' .objs.release/cx_pcre_tables.o:(.rodata+0x88): first defined here ../external/out.release/lib/libpcre.a(pcre_tables.o):(.rodata+0x8c): multiple definition of `_pcre_utf8_table2' .objs.release/cx_pcre_tables.o:(.rodata+0x8c): first defined here ../external/out.release/lib/libpcre.a(pcre_tables.o):(.rodata+0xa4): multiple definition of `_pcre_utf8_table3' .objs.release/cx_pcre_tables.o:(.rodata+0xa4): first defined here ../external/out.release/lib/libpcre.a(pcre_tables.o):(.rodata+0xc0): multiple definition of `_pcre_utf8_table4' .objs.release/cx_pcre_tables.o:(.rodata+0xc0): first defined here ../external/out.release/lib/libpcre.a(pcre_tables.o):(.rodata+0x180): multiple definition of `_pcre_utt_names' .objs.release/cx_pcre_tables.o:(.rodata+0x100): first defined here /usr/bin/ld: Warning: size of symbol `_pcre_utt_names' changed from 657 in .objs.release/cx_pcre_tables.o to 740 in ../external/out.release/lib/libpcre.a(pcre_tables.o) ../external/out.release/lib/libpcre.a(pcre_tables.o):(.rodata+0x480): multiple definition of `_pcre_utt' .objs.release/cx_pcre_tables.o:(.rodata+0x3a0): first defined here /usr/bin/ld: Warning: size of symbol `_pcre_utt' changed from 630 in .objs.release/cx_pcre_tables.o to 696 in ../external/out.release/lib/libpcre.a(pcre_tables.o) ../external/out.release/lib/libpcre.a(pcre_tables.o):(.rodata+0x738): multiple definition of `_pcre_utt_size' .objs.release/cx_pcre_tables.o:(.rodata+0x618): first defined here .objs.release/cx_pcre_exec.o: In function `match(doc_byte_iter, unsigned char const*, doc_byte_iter, int, match_data*, unsigned long, eptrblock*, int, unsigned int)': cx_pcre_exec.cpp:(.text+0x1c2a): undefined reference to `_pcre_ord2utf8(int, unsigned char*)' .objs.release/eauibook.o: In function `eAuiNotebook::LoadPerspective(wxString const&)': eauibook.cpp:(.text+0x9ad): undefined reference to `wxTabFrame::SetTabCtrlHeight(int)' .objs.release/PreviewDlg.o: In function `global constructors keyed to _ZN10PreviewDlg13sm_eventTableE': PreviewDlg.cpp:(.text+0x11b2): undefined reference to `wxEVT_WEB_TITLECHANGE' PreviewDlg.cpp:(.text+0x11ee): undefined reference to `wxEVT_WEB_DOMCONTENTLOADED' .objs.release/PreviewDlg.o: In function `PreviewDlg::RefreshBrowser(PreviewDlg::cxUpdateMode)': PreviewDlg.cpp:(.text+0x2a47): undefined reference to `wxWebControl::OpenURI(wxString const&, unsigned int, wxWebPostData*, bool)' .objs.release/PreviewDlg.o: In function `PreviewDlg::OnWebDocumentComplete(wxWebEvent&)': PreviewDlg.cpp:(.text+0x3259): undefined reference to `wxWebControl::GetCurrentURI() const' .objs.release/PreviewDlg.o: In function `PreviewDlg::PreviewDlg(EditorFrame&)': PreviewDlg.cpp:(.text+0x4984): undefined reference to `wxWebControl::IsInitialized()' PreviewDlg.cpp:(.text+0x49c5): undefined reference to `wxWebControl::wxWebControl(wxWindow*, int, wxPoint const&, wxSize const&)' PreviewDlg.cpp:(.text+0x562f): undefined reference to `wxWebControl::InitEngine(wxString const&)' .objs.release/PreviewDlg.o: In function `PreviewDlg::PreviewDlg(EditorFrame&)': PreviewDlg.cpp:(.text+0x68e4): undefined reference to `wxWebControl::IsInitialized()' PreviewDlg.cpp:(.text+0x6925): undefined reference to `wxWebControl::wxWebControl(wxWindow*, int, wxPoint const&, wxSize const&)' PreviewDlg.cpp:(.text+0x758f): undefined reference to `wxWebControl::InitEngine(wxString const&)' .objs.release/PreviewDlg.o: In function `PreviewDlg::OnButtonForward(wxCommandEvent&)': PreviewDlg.cpp:(.text+0x132): undefined reference to `wxWebControl::GoForward()' .objs.release/PreviewDlg.o: In function `PreviewDlg::OnButtonBack(wxCommandEvent&)': PreviewDlg.cpp:(.text+0x182): undefined reference to `wxWebControl::GoBack()' ../ecore/libecore.so(cxInternal.o): In function `cxInternal::MoveOldSettings(eSettings&)': cxInternal.cpp:(.text+0x4d29): undefined reference to `eSettings::SetPageSettings(unsigned int, wxString const&, doc_id, int, int, wxString const&, std::vector<unsigned int, std::allocator<unsigned int> > const&, std::vector<cxBookmark, std::allocator<cxBookmark> > const&, eSettings::SubPage)' collect2: ld returned 1 exit status make: *** [e] Error 1 EDIT: Forgot the link http://github.com/etexteditor/e

    Read the article

  • simplifying templates

    - by Lodle
    I have a bunch of templates that are used for rpc and was wondering if there is a way to simplify them down as it repeats it self allot. I know varags for templates is coming in the next standard but can you do default values for templates? Also is there a way to handle void functions as normal functions? Atm i have to separate them and treat them as two different things every where. template <typename R> R functionCall(IPC::IPCClass* c, const char* name) { IPC::IPCParameterI* r = c->callFunction( name, false ); return handleReturn<R>(r); } template <typename R, typename A> R functionCall(IPC::IPCClass* cl, const char* name, A a) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a)); return handleReturn<R>(r); } template <typename R, typename A, typename B> R functionCall(IPC::IPCClass* cl, const char* name, A a, B b) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b) ); return handleReturn<R>(r); } template <typename R, typename A, typename B, typename C> R functionCall(IPC::IPCClass* cl, const char* name, A a, B b, C c) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c) ); return handleReturn<R>(r); } template <typename R, typename A, typename B, typename C, typename D> R functionCall(IPC::IPCClass* cl, const char* name, A a, B b, C c, D d) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c), IPC::getParameter(d) ); return handleReturn<R>(r); } template <typename R, typename A, typename B, typename C, typename D, typename E> R functionCall(IPC::IPCClass* cl, const char* name, A a, B b, C c, D d, E e) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c), IPC::getParameter(d), IPC::getParameter(e) ); return handleReturn<R>(r); } template <typename R, typename A, typename B, typename C, typename D, typename E, typename F> R functionCall(IPC::IPCClass* cl, const char* name, A a, B b, C c, D d, E e, F f) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c), IPC::getParameter(d), IPC::getParameter(e), IPC::getParameter(f) ); return handleReturn<R>(r); } inline void functionCallV(IPC::IPCClass* cl, const char* name) { IPC::IPCParameterI* r = cl->callFunction( name, false ); handleReturnV(r); } template <typename A> void functionCallV(IPC::IPCClass* cl, const char* name, A a) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a)); handleReturnV(r); } template <typename A, typename B> void functionCallV(IPC::IPCClass* cl, const char* name, A a, B b) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b) ); handleReturnV(r); } template <typename A, typename B, typename C> void functionCallV(IPC::IPCClass* cl, const char* name, A a, B b, C c) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c) ); handleReturnV(r); } template <typename A, typename B, typename C, typename D> void functionCallV(IPC::IPCClass* cl, const char* name, A a, B b, C c, D d) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c), IPC::getParameter(d) ); handleReturnV(r); } template <typename A, typename B, typename C, typename D, typename E> void functionCallV(IPC::IPCClass* cl, const char* name, A a, B b, C c, D d, E e) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c), IPC::getParameter(d), IPC::getParameter(e) ); handleReturnV(r); } template <typename A, typename B, typename C, typename D, typename E, typename F> void functionCallV(IPC::IPCClass* cl, const char* name, A a, B b, C c, D d, E e, F f) { IPC::IPCParameterI* r = cl->callFunction( name, false, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c), IPC::getParameter(d), IPC::getParameter(e), IPC::getParameter(f) ); handleReturnV(r); } inline void functionCallAsync(IPC::IPCClass* cl, const char* name) { IPC::IPCParameterI* r = cl->callFunction( name, true ); handleReturnV(r); } template <typename A> void functionCallAsync(IPC::IPCClass* cl, const char* name, A a) { IPC::IPCParameterI* r = cl->callFunction( name, true, IPC::getParameter(a)); handleReturnV(r); } template <typename A, typename B> void functionCallAsync(IPC::IPCClass* cl, const char* name, A a, B b) { IPC::IPCParameterI* r = cl->callFunction( name, true, IPC::getParameter(a), IPC::getParameter(b) ); handleReturnV(r); } template <typename A, typename B, typename C> void functionCallAsync(IPC::IPCClass* cl, const char* name, A a, B b, C c) { IPC::IPCParameterI* r = cl->callFunction( name, true, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c) ); handleReturnV(r); } template <typename A, typename B, typename C, typename D> void functionCallAsync(IPC::IPCClass* cl, const char* name, A a, B b, C c, D d) { IPC::IPCParameterI* r = cl->callFunction( name, true, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c), IPC::getParameter(d) ); handleReturnV(r); } template <typename A, typename B, typename C, typename D, typename E> void functionCallAsync(IPC::IPCClass* cl, const char* name, A a, B b, C c, D d, E e) { IPC::IPCParameterI* r = cl->callFunction( name, true, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c), IPC::getParameter(d), IPC::getParameter(e) ); handleReturnV(r); } template <typename A, typename B, typename C, typename D, typename E, typename F> void functionCallAsync(IPC::IPCClass* cl, const char* name, A a, B b, C c, D d, E e, F f) { IPC::IPCParameterI* r = cl->callFunction( name, true, IPC::getParameter(a), IPC::getParameter(b), IPC::getParameter(c), IPC::getParameter(d), IPC::getParameter(e), IPC::getParameter(f) ); handleReturnV(r); }

    Read the article

  • C++ addition overload ambiguity

    - by Nate
    I am coming up against a vexing conundrum in my code base. I can't quite tell why my code generates this error, but (for example) std::string does not. class String { public: String(const char*str); friend String operator+ ( const String& lval, const char *rval ); friend String operator+ ( const char *lval, const String& rval ); String operator+ ( const String& rval ); }; The implementation of these is easy enough to imagine on your own. My driver program contains the following: String result, lval("left side "), rval("of string"); char lv[] = "right side ", rv[] = "of string"; result = lv + rval; printf(result); result = (lval + rv); printf(result); Which generates the following error in gcc 4.1.2: driver.cpp:25: error: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: String.h:22: note: candidate 1: String operator+(const String&, const char*) String.h:24: note: candidate 2: String String::operator+(const String&) So far so good, right? Sadly, my String(const char *str) constructor is so handy to have as an implicit constructor, that using the explicit keyword to solve this would just cause a different pile of problems. Moreover... std::string doesn't have to resort to this, and I can't figure out why. For example, in basic_string.h, they are declared as follows: template<typename _CharT, typename _Traits, typename _Alloc> basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) template<typename _CharT, typename _Traits, typename _Alloc> basic_string<_CharT,_Traits,_Alloc> operator+(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Alloc>& __rhs); and so on. The basic_string constructor is not declared explicit. How does this not cause the same error I'm getting, and how can I achieve the same behavior??

    Read the article

  • best alternative to in-definition initialization of static class members? (for SVN keywords)

    - by Jeff
    I'm storing expanded SVN keyword literals for .cpp files in 'static char const *const' class members and want to store the .h descriptions as similarly as possible. In short, I need to guarantee single instantiation of a static member (presumably in a .cpp file) to an auto-generated non-integer literal living in a potentially shared .h file. Unfortunately the language makes no attempt to resolve multiple instantiations resulting from assignments made outside class definitions and explicitly forbids non-integer inits inside class definitions. My best attempt (using static-wrapping internal classes) is not too dirty, but I'd really like to do better. Does anyone have a way to template the wrapper below or have an altogether superior approach? // Foo.h: class with .h/.cpp SVN info stored and logged statically class Foo { static Logger const verLog; struct hInfoWrap; public: static hInfoWrap const hInfo; static char const *const cInfo; }; // Would like to eliminate this per-class boilerplate. struct Foo::hInfoWrap { hInfoWrapper() : text("$Id$") { } char const *const text; }; ... // Foo.cpp: static inits called here Foo::hInfoWrap const Foo::hInfo; char const *const Foo::cInfo = "$Id$"; Logger const Foo::verLog(Foo::cInfo, Foo::hInfo.text); ... // Helper.h: output on construction, with no subsequent activity or stored fields class Logger { Logger(char const *info1, char const *info2) { cout << info0 << endl << info1 << endl; } }; Is there a way to get around the static linkage address issue for templating the hInfoWrap class on string literals? Extern char pointers assigned outside class definitions are linguistically valid but fail in essentially the same manner as direct member initializations. I get why the language shirks the whole resolution issue, but it'd be very convenient if an inverted extern member qualifier were provided, where the definition code was visible in class definitions to any caller but only actually invoked at the point of a single special declaration elsewhere. Anyway, I digress. What's the best solution for the language we've got, template or otherwise? Thanks!

    Read the article

  • What are the implications of using static const instead of #define?

    - by Simon Elliott
    gcc complains about this: #include <stdio.h> static const int YY = 1024; extern int main(int argc, char*argv[]) { static char x[YY]; } $ gcc -c test1.c test1.c: In function main': test1.c:5: error: storage size of x' isn't constant test1.c:5: error: size of variable `x' is too large Remove the “static” from the definition of x and all is well. I'm not exactly clear what's going on here: surely YY is constant? I had always assumed that the "static const" approach was preferable to "#define". Is there any way of using "static const" in this situation?

    Read the article

  • Vertex buffer acting strange? [on hold]

    - by Ryan Capote
    I'm having a strange problem, and I don't know what could be causing it. My current code is identical to how I've done this before. I'm trying to render a rectangle using VBO and orthographic projection.   My results:     What I expect: 3x3 rectangle in the top left corner   #include <stdio.h> #include <GL\glew.h> #include <GLFW\glfw3.h> #include "lodepng.h"   static const int FALSE = 0; static const int TRUE = 1;   static const char* VERT_SHADER =     "#version 330\n"       "layout(location=0) in vec4 VertexPosition; "     "layout(location=1) in vec2 UV;"     "uniform mat4 uProjectionMatrix;"     /*"out vec2 TexCoords;"*/       "void main(void) {"     "    gl_Position = uProjectionMatrix*VertexPosition;"     /*"    TexCoords = UV;"*/     "}";   static const char* FRAG_SHADER =     "#version 330\n"       /*"uniform sampler2D uDiffuseTexture;"     "uniform vec4 uColor;"     "in vec2 TexCoords;"*/     "out vec4 FragColor;"       "void main(void) {"    /* "    vec4 texel = texture2D(uDiffuseTexture, TexCoords);"     "    if(texel.a <= 0) {"     "         discard;"     "    }"     "    FragColor = texel;"*/     "    FragColor = vec4(1.f);"     "}";   static int g_running; static GLFWwindow *gl_window; static float gl_projectionMatrix[16];   /*     Structures */ typedef struct _Vertex {     float x, y, z, w;     float u, v; } Vertex;   typedef struct _Position {     float x, y; } Position;   typedef struct _Bitmap {     unsigned char *pixels;     unsigned int width, height; } Bitmap;   typedef struct _Texture {     GLuint id;     unsigned int width, height; } Texture;   typedef struct _VertexBuffer {     GLuint bufferObj, vertexArray; } VertexBuffer;   typedef struct _ShaderProgram {     GLuint vertexShader, fragmentShader, program; } ShaderProgram;   /*   http://en.wikipedia.org/wiki/Orthographic_projection */ void createOrthoProjection(float *projection, float width, float height, float far, float near)  {       const float left = 0;     const float right = width;     const float top = 0;     const float bottom = height;          projection[0] = 2.f / (right - left);     projection[1] = 0.f;     projection[2] = 0.f;     projection[3] = -(right+left) / (right-left);     projection[4] = 0.f;     projection[5] = 2.f / (top - bottom);     projection[6] = 0.f;     projection[7] = -(top + bottom) / (top - bottom);     projection[8] = 0.f;     projection[9] = 0.f;     projection[10] = -2.f / (far-near);     projection[11] = (far+near)/(far-near);     projection[12] = 0.f;     projection[13] = 0.f;     projection[14] = 0.f;     projection[15] = 1.f; }   /*     Textures */ void loadBitmap(const char *filename, Bitmap *bitmap, int *success) {     int error = lodepng_decode32_file(&bitmap->pixels, &bitmap->width, &bitmap->height, filename);       if (error != 0) {         printf("Failed to load bitmap. ");         printf(lodepng_error_text(error));         success = FALSE;         return;     } }   void destroyBitmap(Bitmap *bitmap) {     free(bitmap->pixels); }   void createTexture(Texture *texture, const Bitmap *bitmap) {     texture->id = 0;     glGenTextures(1, &texture->id);     glBindTexture(GL_TEXTURE_2D, texture);       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);       glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bitmap->width, bitmap->height, 0,              GL_RGBA, GL_UNSIGNED_BYTE, bitmap->pixels);       glBindTexture(GL_TEXTURE_2D, 0); }   void destroyTexture(Texture *texture) {     glDeleteTextures(1, &texture->id);     texture->id = 0; }   /*     Vertex Buffer */ void createVertexBuffer(VertexBuffer *vertexBuffer, Vertex *vertices) {     glGenBuffers(1, &vertexBuffer->bufferObj);     glGenVertexArrays(1, &vertexBuffer->vertexArray);     glBindVertexArray(vertexBuffer->vertexArray);       glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer->bufferObj);     glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * 6, (const GLvoid*)vertices, GL_STATIC_DRAW);       const unsigned int uvOffset = sizeof(float) * 4;       glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);     glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)uvOffset);       glEnableVertexAttribArray(0);     glEnableVertexAttribArray(1);       glBindBuffer(GL_ARRAY_BUFFER, 0);     glBindVertexArray(0); }   void destroyVertexBuffer(VertexBuffer *vertexBuffer) {     glDeleteBuffers(1, &vertexBuffer->bufferObj);     glDeleteVertexArrays(1, &vertexBuffer->vertexArray); }   void bindVertexBuffer(VertexBuffer *vertexBuffer) {     glBindVertexArray(vertexBuffer->vertexArray);     glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer->bufferObj); }   void drawVertexBufferMode(GLenum mode) {     glDrawArrays(mode, 0, 6); }   void drawVertexBuffer() {     drawVertexBufferMode(GL_TRIANGLES); }   void unbindVertexBuffer() {     glBindVertexArray(0);     glBindBuffer(GL_ARRAY_BUFFER, 0); }   /*     Shaders */ void compileShader(ShaderProgram *shaderProgram, const char *vertexSrc, const char *fragSrc) {     GLenum err;     shaderProgram->vertexShader = glCreateShader(GL_VERTEX_SHADER);     shaderProgram->fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);       if (shaderProgram->vertexShader == 0) {         printf("Failed to create vertex shader.");         return;     }       if (shaderProgram->fragmentShader == 0) {         printf("Failed to create fragment shader.");         return;     }       glShaderSource(shaderProgram->vertexShader, 1, &vertexSrc, NULL);     glCompileShader(shaderProgram->vertexShader);     glGetShaderiv(shaderProgram->vertexShader, GL_COMPILE_STATUS, &err);       if (err != GL_TRUE) {         printf("Failed to compile vertex shader.");         return;     }       glShaderSource(shaderProgram->fragmentShader, 1, &fragSrc, NULL);     glCompileShader(shaderProgram->fragmentShader);     glGetShaderiv(shaderProgram->fragmentShader, GL_COMPILE_STATUS, &err);       if (err != GL_TRUE) {         printf("Failed to compile fragment shader.");         return;     }       shaderProgram->program = glCreateProgram();     glAttachShader(shaderProgram->program, shaderProgram->vertexShader);     glAttachShader(shaderProgram->program, shaderProgram->fragmentShader);     glLinkProgram(shaderProgram->program);          glGetProgramiv(shaderProgram->program, GL_LINK_STATUS, &err);       if (err != GL_TRUE) {         printf("Failed to link shader.");         return;     } }   void destroyShader(ShaderProgram *shaderProgram) {     glDetachShader(shaderProgram->program, shaderProgram->vertexShader);     glDetachShader(shaderProgram->program, shaderProgram->fragmentShader);       glDeleteShader(shaderProgram->vertexShader);     glDeleteShader(shaderProgram->fragmentShader);       glDeleteProgram(shaderProgram->program); }   GLuint getUniformLocation(const char *name, ShaderProgram *program) {     GLuint result = 0;     result = glGetUniformLocation(program->program, name);       return result; }   void setUniformMatrix(float *matrix, const char *name, ShaderProgram *program) {     GLuint loc = getUniformLocation(name, program);       if (loc == -1) {         printf("Failed to get uniform location in setUniformMatrix.\n");         return;     }       glUniformMatrix4fv(loc, 1, GL_FALSE, matrix); }   /*     General functions */ static int isRunning() {     return g_running && !glfwWindowShouldClose(gl_window); }   static void initializeGLFW(GLFWwindow **window, int width, int height, int *success) {     if (!glfwInit()) {         printf("Failed it inialize GLFW.");         *success = FALSE;        return;     }          glfwWindowHint(GLFW_RESIZABLE, 0);     *window = glfwCreateWindow(width, height, "Alignments", NULL, NULL);          if (!*window) {         printf("Failed to create window.");         glfwTerminate();         *success = FALSE;         return;     }          glfwMakeContextCurrent(*window);       GLenum glewErr = glewInit();     if (glewErr != GLEW_OK) {         printf("Failed to initialize GLEW.");         printf(glewGetErrorString(glewErr));         *success = FALSE;         return;     }       glClearColor(0.f, 0.f, 0.f, 1.f);     glViewport(0, 0, width, height);     *success = TRUE; }   int main(int argc, char **argv) {          int err = FALSE;     initializeGLFW(&gl_window, 480, 320, &err);     glDisable(GL_DEPTH_TEST);     if (err == FALSE) {         return 1;     }          createOrthoProjection(gl_projectionMatrix, 480.f, 320.f, 0.f, 1.f);          g_running = TRUE;          ShaderProgram shader;     compileShader(&shader, VERT_SHADER, FRAG_SHADER);     glUseProgram(shader.program);     setUniformMatrix(&gl_projectionMatrix, "uProjectionMatrix", &shader);       Vertex rectangle[6];     VertexBuffer vbo;     rectangle[0] = (Vertex){0.f, 0.f, 0.f, 1.f, 0.f, 0.f}; // Top left     rectangle[1] = (Vertex){3.f, 0.f, 0.f, 1.f, 1.f, 0.f}; // Top right     rectangle[2] = (Vertex){0.f, 3.f, 0.f, 1.f, 0.f, 1.f}; // Bottom left     rectangle[3] = (Vertex){3.f, 0.f, 0.f, 1.f, 1.f, 0.f}; // Top left     rectangle[4] = (Vertex){0.f, 3.f, 0.f, 1.f, 0.f, 1.f}; // Bottom left     rectangle[5] = (Vertex){3.f, 3.f, 0.f, 1.f, 1.f, 1.f}; // Bottom right       createVertexBuffer(&vbo, &rectangle);            bindVertexBuffer(&vbo);          while (isRunning()) {         glClear(GL_COLOR_BUFFER_BIT);         glfwPollEvents();                    drawVertexBuffer();                    glfwSwapBuffers(gl_window);     }          unbindVertexBuffer(&vbo);       glUseProgram(0);     destroyShader(&shader);     destroyVertexBuffer(&vbo);     glfwTerminate();     return 0; }

    Read the article

  • Object array updates one instance repeatedly [on hold]

    - by MGN001
    I'm making a 2D shooter, and the player object holds an array of bullets that represent how many shots the player can have on screen at once. At least, this is what I'm trying for. What's happening is that each time any of the objects in the array is called, it seems to update a single object in memory. So, if I fire and then fire again, the object "starts over" from where I shot from and moves twice as fast. I've spent weeks trying to fix this and I've managed nothing. Hopefully another pair of eyes will see something I've missed. Player.cpp #include "Player.h" const int startLives = 3; const int maxHealth = 2; const float speed = 1; const int maxVelocity = 500; const int topBound = WINDOW_HEIGHT / 5 * 3; const int slowRate = 500; const int accRate = 1000; const int maxBullets = 5; const float spriteWidth = 99; const float spriteHeight = 75; const Vector2f startPosition = { (WINDOW_WIDTH / 2) - (spriteWidth / 2), (WINDOW_HEIGHT / 4 * 3) - (spriteHeight / 2) }; Bullet bullets[maxBullets]; Bullet * bulletPointers[maxBullets]; SDL_Texture * playerHealthy; SDL_Texture * playerDamaged; SDL_Texture * currentSprite; SDL_Rect * rect; Vector2f position; Vector2f velocity; int Health; int Lives; Player::Player() { rect = new SDL_Rect(); } Player::~Player() { SDL_DestroyTexture(playerHealthy); SDL_DestroyTexture(playerDamaged); SDL_DestroyTexture(currentSprite); rect = NULL; } void Player::Initialize(SDL_Renderer * renderer) { SDL_Surface * temp; temp = IMG_Load(".\\Sprites\\player.png"); if (temp == NULL) { printf("Initialization Error: %s\n", IMG_GetError()); exit(PLAYER_INITIALIZATION_ERROR); } playerHealthy = SDL_CreateTextureFromSurface(renderer, temp); temp = IMG_Load(".\\Sprites\\playerDamaged.png"); if (temp == NULL) { printf("Initialization Error: %s\n", IMG_GetError()); exit(PLAYER_INITIALIZATION_ERROR); } playerDamaged = SDL_CreateTextureFromSurface(renderer, temp); temp = IMG_Load(".\\Sprites\\laserGreen.png"); if (temp == NULL) { printf("Initialization Error: %s\n", IMG_GetError()); exit(PLAYER_INITIALIZATION_ERROR); } SDL_Texture * bullet = SDL_CreateTextureFromSurface(renderer, temp); temp = IMG_Load(".\\Sprites\\laserGreenShot.png"); if (temp == NULL) { printf("Initialization Error: %s\n", IMG_GetError()); exit(PLAYER_INITIALIZATION_ERROR); } SDL_Texture * explosion = SDL_CreateTextureFromSurface(renderer, temp); for (int i = 0; i < maxBullets; i++) { bullets[i].Initialize(renderer, bullet, explosion); bulletPointers[i] = NULL; } temp = NULL; rect->h = spriteHeight; rect->w = spriteWidth; Reset(); } void Player::Update(Input input, float deltaTime) { if (abs(velocity.x) < slowRate * deltaTime) { velocity.x = 0; } else if (velocity.x > 0) { velocity.x -= slowRate * deltaTime; } else if (velocity.x < 0) { velocity.x += slowRate * deltaTime; } if (abs(velocity.y) < slowRate * deltaTime) { velocity.y = 0; } if (velocity.y > 0) { velocity.y -= slowRate * deltaTime; } else if (velocity.y < 0) { velocity.y += slowRate * deltaTime; } if (Health <= 0) { --Lives; Spawn(); } velocity.x += UnitVector(input.InputNew.movement).x * accRate * deltaTime; velocity.y += UnitVector(input.InputNew.movement).y * accRate * deltaTime; if (Magnitude(velocity) > maxVelocity) { velocity.x = UnitVector(velocity).x * maxVelocity; velocity.y = UnitVector(velocity).y * maxVelocity; } position.x += velocity.x * deltaTime * speed; position.y += velocity.y * deltaTime * speed; if (input.InputNew.JumpLeft && !input.InputOld.JumpLeft) { position.x -= spriteWidth; } if (input.InputNew.JumpRight && !input.InputOld.JumpRight) { position.x += spriteWidth; } Boundaries(); rect->x = position.x; rect->y = position.y; if (input.InputNew.Fire && !input.InputOld.Fire) { Fire(); } for (int i = 0; i < maxBullets; ++i) { if (bulletPointers[i] != NULL) { bullets[i].Update(deltaTime); if (bullets[i].getPosition().y < -33) { bulletPointers[i] = NULL; } } } } void Player::Draw(SDL_Renderer * renderer) { for (int i = 0; i < maxBullets; ++i) { if (bulletPointers[i] != NULL) { bullets[i].Draw(renderer); } } SDL_RenderCopy(renderer, currentSprite, NULL, rect); } void Player::Spawn() { position = startPosition; Health = maxHealth; currentSprite = playerHealthy; rect->x = position.x; rect->y = position.y; } void Player::Boundaries() { if (position.x < 0) { position.x = 0; velocity.x *= -1; } else if (position.x > WINDOW_WIDTH - spriteWidth) { position.x = WINDOW_WIDTH - spriteWidth; velocity.x *= -1; } if (position.y < topBound) { position.y = topBound; velocity.y *= -1; } else if (position.y > WINDOW_HEIGHT - spriteHeight) { position.y = WINDOW_HEIGHT - spriteHeight; velocity.y *= -1; } } int Player::getLives() { return Lives; } void Player::Reset() { Lives = startLives; Spawn(); } void Player::Fire() { for (int i = 0; i < maxBullets; ++i) { if (bulletPointers[i] == NULL) { bulletPointers[i] = &bullets[i]; bullets[i].Fire(position,velocity.x/2); break; } } } Bullet.cpp #include "Bullet.h" const int speed = 500; Vector2f bulletVelocity; float ExplosionMax = 0.5f; float ExplosionTimer; const Vector2f fireOffset = { 45.5f, 10.0f }; const Vector2f explosionOffset = { 23.5f, -27.0f }; const Vector2i bulletSize = { 9, 33 }; const Vector2i explosionSize = { 56, 54 }; Vector2f bulletPosition; SDL_Texture * bulletSprite; SDL_Texture * explosionSprite; SDL_Texture * bulletCurrentSprite; SDL_Rect * bulletRect; Bullet::Bullet() { } Bullet::~Bullet() { } void Bullet::Initialize(SDL_Renderer * renderer, SDL_Texture * bullet, SDL_Texture * explosion) { bulletSprite = bullet; explosionSprite = explosion; bulletRect = new SDL_Rect(); } void Bullet::Update(float deltaTime) { bulletPosition.y -= bulletVelocity.y * deltaTime; bulletPosition.x += bulletVelocity.x * deltaTime; bulletRect->x = static_cast<int>(bulletPosition.x); bulletRect->y = static_cast<int>(bulletPosition.y); } void Bullet::Draw(SDL_Renderer * renderer) { SDL_RenderCopy(renderer, bulletCurrentSprite, NULL, bulletRect); } void Bullet::Fire(Vector2f pos, float xSpeed) { bulletPosition.x = pos.x + fireOffset.x; bulletPosition.y = pos.y + fireOffset.y; bulletVelocity.x = xSpeed; bulletVelocity.y = speed; bulletCurrentSprite = bulletSprite; bulletRect->h = bulletSize.y; bulletRect->w = bulletSize.x; bulletRect->x = static_cast<int>(bulletPosition.x); bulletRect->y = static_cast<int>(bulletPosition.y); } Vector2f Bullet::getPosition() { return bulletPosition; } void Bullet::Hit() { bulletCurrentSprite = explosionSprite; bulletVelocity = { 0.0f, 0.0f }; ExplosionTimer = ExplosionMax; bulletPosition.x += explosionOffset.x; bulletPosition.y += explosionOffset.y; bulletRect->w = explosionSize.x; bulletRect->h = explosionSize.y; }

    Read the article

  • Espeak SAPI/dll usage on Windows ?

    - by Quandary
    Question: I am trying to use the espeak text-to-speech engine. So for I got it working wounderfully on linux (code below). Now I wanted to port this basic program to windows, too, but it's nearly impossible... Part of the problem is that the windows dll only allows for AUDIO_OUTPUT_SYNCHRONOUS, which means it requires a callback, but I can't figure out how to play the audio from the callback... First it crashed, then I realized, I need a callback function, now I get the data in the callback function, but I don't know how to play it... as it is neither a wav file nor plays automatically as on Linux. The sourceforge site is rather useless, because it basically says use the SAPI version, but then there is no example on how to use the sapi espeak dll... Anyway, here's my code, can anybody help? #ifdef __cplusplus #include <cstdio> #include <cstdlib> #include <cstring> else #include <stdio.h> #include <stdlib.h> #include <string.h> endif include include //#include "speak_lib.h" include "espeak/speak_lib.h" // libespeak-dev: /usr/include/espeak/speak_lib.h // apt-get install libespeak-dev // apt-get install libportaudio-dev // g++ -o mine mine.cpp -lespeak // g++ -o mine mine.cpp -I/usr/include/espeak/ -lespeak // gcc -o mine mine.cpp -I/usr/include/espeak/ -lespeak char voicename[40]; int samplerate; int quiet = 0; static char genders[4] = {' ','M','F',' '}; //const char *data_path = "/usr/share/"; // /usr/share/espeak-data/ const char *data_path = NULL; // use default path for espeak-data int strrcmp(const char *s, const char *sub) { int slen = strlen(s); int sublen = strlen(sub); return memcmp(s + slen - sublen, sub, sublen); } char * strrcpy(char *dest, const char *source) { // Pre assertions assert(dest != NULL); assert(source != NULL); assert(dest != source); // tk: parentheses while((*dest++ = *source++)) ; return(--dest); } const char* GetLanguageVoiceName(const char* pszShortSign) { #define LANGUAGE_LENGTH 30 static char szReturnValue[LANGUAGE_LENGTH] ; memset(szReturnValue, 0, LANGUAGE_LENGTH); for (int i = 0; pszShortSign[i] != '\0'; ++i) szReturnValue[i] = (char) tolower(pszShortSign[i]); const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { if( !strrcmp( v->languages, szReturnValue) ) { strcpy(szReturnValue, v->name); return szReturnValue; } } // End for strcpy(szReturnValue, "default"); return szReturnValue; } // End function getvoicename void ListVoices() { const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { printf("Shortsign: %s\n", v->languages); printf("age: %d\n", v->age); printf("gender: %c\n", genders[v->gender]); printf("name: %s\n", v->name); printf("\n\n"); } // End for } // End function getvoicename int main() { printf("Hello World!\n"); const char* szVersionInfo = espeak_Info(NULL); printf("Espeak version: %s\n", szVersionInfo); samplerate = espeak_Initialize(AUDIO_OUTPUT_PLAYBACK,0,data_path,0); strcpy(voicename, "default"); // espeak --voices strcpy(voicename, "german"); strcpy(voicename, GetLanguageVoiceName("DE")); if(espeak_SetVoiceByName(voicename) != EE_OK) { printf("Espeak setvoice error...\n"); } static char word[200] = "Hello World" ; strcpy(word, "TV-fäns aufgepasst, es ist 20 Uhr 15. Zeit für Rambo 3"); strcpy(word, "Unnamed Player wurde zum Opfer von GSG9"); int speed = 220; int volume = 500; // volume in range 0-100 0=silence int pitch = 50; // base pitch, range 0-100. 50=normal // espeak.cpp 625 espeak_SetParameter(espeakRATE, speed, 0); espeak_SetParameter(espeakVOLUME,volume,0); espeak_SetParameter(espeakPITCH,pitch,0); // espeakRANGE: pitch range, range 0-100. 0-monotone, 50=normal // espeakPUNCTUATION: which punctuation characters to announce: // value in espeak_PUNCT_TYPE (none, all, some), espeak_VOICE *voice_spec = espeak_GetCurrentVoice(); voice_spec->gender=2; // 0=none 1=male, 2=female, //voice_spec->age = age; espeak_SetVoiceByProperties(voice_spec); espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); espeak_Synchronize(); strcpy(voicename, GetLanguageVoiceName("EN")); espeak_SetVoiceByName(voicename); strcpy(word, "Geany was fragged by GSG9 Googlebot"); strcpy(word, "Googlebot"); espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); espeak_Synchronize(); espeak_Terminate(); printf("Espeak terminated\n"); return EXIT_SUCCESS; } /* if(espeak_SetVoiceByName(voicename) != EE_OK) { memset(&voice_select,0,sizeof(voice_select)); voice_select.languages = voicename; if(espeak_SetVoiceByProperties(&voice_select) != EE_OK) { fprintf(stderr,"%svoice '%s'\n",err_load,voicename); exit(2); } } */ The above code is for Linux. The below code is about as far as I got on Vista x64 (32 bit emu): #ifdef __cplusplus #include <cstdio> #include <cstdlib> #include <cstring> else #include <stdio.h> #include <stdlib.h> #include <string.h> endif include include include "speak_lib.h" //#include "espeak/speak_lib.h" // libespeak-dev: /usr/include/espeak/speak_lib.h // apt-get install libespeak-dev // apt-get install libportaudio-dev // g++ -o mine mine.cpp -lespeak // g++ -o mine mine.cpp -I/usr/include/espeak/ -lespeak // gcc -o mine mine.cpp -I/usr/include/espeak/ -lespeak char voicename[40]; int iSampleRate; int quiet = 0; static char genders[4] = {' ','M','F',' '}; //const char *data_path = "/usr/share/"; // /usr/share/espeak-data/ //const char *data_path = NULL; // use default path for espeak-data const char *data_path = "C:\Users\Username\Desktop\espeak-1.43-source\espeak-1.43-source\"; int strrcmp(const char *s, const char *sub) { int slen = strlen(s); int sublen = strlen(sub); return memcmp(s + slen - sublen, sub, sublen); } char * strrcpy(char *dest, const char *source) { // Pre assertions assert(dest != NULL); assert(source != NULL); assert(dest != source); // tk: parentheses while((*dest++ = *source++)) ; return(--dest); } const char* GetLanguageVoiceName(const char* pszShortSign) { #define LANGUAGE_LENGTH 30 static char szReturnValue[LANGUAGE_LENGTH] ; memset(szReturnValue, 0, LANGUAGE_LENGTH); for (int i = 0; pszShortSign[i] != '\0'; ++i) szReturnValue[i] = (char) tolower(pszShortSign[i]); const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { if( !strrcmp( v->languages, szReturnValue) ) { strcpy(szReturnValue, v->name); return szReturnValue; } } // End for strcpy(szReturnValue, "default"); return szReturnValue; } // End function getvoicename void ListVoices() { const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { printf("Shortsign: %s\n", v->languages); printf("age: %d\n", v->age); printf("gender: %c\n", genders[v->gender]); printf("name: %s\n", v->name); printf("\n\n"); } // End for } // End function getvoicename /* Callback from espeak. Directly speaks using AudioTrack. */ define LOGI(x) printf("%s\n", x) static int AndroidEspeakDirectSpeechCallback(short *wav, int numsamples, espeak_EVENT *events) { char buf[100]; sprintf(buf, "AndroidEspeakDirectSpeechCallback: %d samples", numsamples); LOGI(buf); if (wav == NULL) { LOGI("Null: speech has completed"); } if (numsamples > 0) { //audout->write(wav, sizeof(short) * numsamples); sprintf(buf, "AudioTrack wrote: %d bytes", sizeof(short) * numsamples); LOGI(buf); } return 0; // continue synthesis (1 is to abort) } static int AndroidEspeakSynthToFileCallback(short *wav, int numsamples,espeak_EVENT *events) { char buf[100]; sprintf(buf, "AndroidEspeakSynthToFileCallback: %d samples", numsamples); LOGI(buf); if (wav == NULL) { LOGI("Null: speech has completed"); } // The user data should contain the file pointer of the file to write to //void* user_data = events->user_data; FILE* user_data = fopen ( "myfile1.wav" , "ab" ); FILE* fp = static_cast<FILE *>(user_data); // Write all of the samples fwrite(wav, sizeof(short), numsamples, fp); return 0; // continue synthesis (1 is to abort) } int main() { printf("Hello World!\n"); const char* szVersionInfo = espeak_Info(NULL); printf("Espeak version: %s\n", szVersionInfo); iSampleRate = espeak_Initialize(AUDIO_OUTPUT_SYNCHRONOUS, 4096, data_path, 0); if (iSampleRate <= 0) { printf("Unable to initialize espeak"); return EXIT_FAILURE; } //samplerate = espeak_Initialize(AUDIO_OUTPUT_PLAYBACK,0,data_path,0); //ListVoices(); strcpy(voicename, "default"); // espeak --voices //strcpy(voicename, "german"); //strcpy(voicename, GetLanguageVoiceName("DE")); if(espeak_SetVoiceByName(voicename) != EE_OK) { printf("Espeak setvoice error...\n"); } static char word[200] = "Hello World" ; strcpy(word, "TV-fäns aufgepasst, es ist 20 Uhr 15. Zeit für Rambo 3"); strcpy(word, "Unnamed Player wurde zum Opfer von GSG9"); int speed = 220; int volume = 500; // volume in range 0-100 0=silence int pitch = 50; // base pitch, range 0-100. 50=normal // espeak.cpp 625 espeak_SetParameter(espeakRATE, speed, 0); espeak_SetParameter(espeakVOLUME,volume,0); espeak_SetParameter(espeakPITCH,pitch,0); // espeakRANGE: pitch range, range 0-100. 0-monotone, 50=normal // espeakPUNCTUATION: which punctuation characters to announce: // value in espeak_PUNCT_TYPE (none, all, some), //espeak_VOICE *voice_spec = espeak_GetCurrentVoice(); //voice_spec->gender=2; // 0=none 1=male, 2=female, //voice_spec->age = age; //espeak_SetVoiceByProperties(voice_spec); //espeak_SetSynthCallback(AndroidEspeakDirectSpeechCallback); espeak_SetSynthCallback(AndroidEspeakSynthToFileCallback); unsigned int unique_identifier; espeak_ERROR err = espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, &unique_identifier, NULL); err = espeak_Synchronize(); /* strcpy(voicename, GetLanguageVoiceName("EN")); espeak_SetVoiceByName(voicename); strcpy(word, "Geany was fragged by GSG9 Googlebot"); strcpy(word, "Googlebot"); espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); espeak_Synchronize(); */ // espeak_Cancel(); espeak_Terminate(); printf("Espeak terminated\n"); system("pause"); return EXIT_SUCCESS; }

    Read the article

  • How to keep g++ from taking header file from /usr/include?

    - by WilliamKF
    I am building using zlib.h which I have a local copy to v1.2.5, but in /usr/include/zlib.h there is v1.2.1.2. If I omit adding -I/my/path/to/zlib to my make I get error from using old version which doesn't have Z_FIXED: g++ -g -Werror -Wredundant-decls -D_FILE_OFFSET_BITS=64 -c -o ARCH.linux_26_i86/debug/sysParam.o sysParam.cpp sysParam.cpp: In member function `std::string CSysParamAccess::getCompressionStrategyName() const': sysParam.cpp:1816: error: `Z_FIXED' was not declared in this scope sysParam.cpp: In member function `bool CSysParamAccess::setCompressionStrategy(const std::string&, paramSource)': sysParam.cpp:1849: error: `Z_FIXED' was not declared in this scope Alternatively, if I add the include path to the zlib z1.2.5 I am using, I get double defines, it seems as if the zlib.h is included twice with two different sets of -D values, but I don't see how that is happening: g++ -g -Werror -Wredundant-decls -I../../src/zlib-1.2.5 -D_FILE_OFFSET_BITS=64 -c -o ARCH.linux_26_i86/debug/sysParam.o sysParam.cpp In file included from sysParam.cpp:24: ../../src/zlib-1.2.5/zlib.h:1582: warning: redundant redeclaration of `void* gzopen64(const char*, const char*)' in same scope ../../src/zlib-1.2.5/zlib.h:1566: warning: previous declaration of `void* gzopen64(const char*, const char*)' ../../src/zlib-1.2.5/zlib.h:1583: warning: redundant redeclaration of `long long int gzseek64(void*, long long int, int)' in same scope ../../src/zlib-1.2.5/zlib.h:1567: warning: previous declaration of `off64_t gzseek64(void*, off64_t, int)' ../../src/zlib-1.2.5/zlib.h:1584: warning: redundant redeclaration of `long long int gztell64(void*)' in same scope ../../src/zlib-1.2.5/zlib.h:1568: warning: previous declaration of `off64_t gztell64(void*)' ../../src/zlib-1.2.5/zlib.h:1585: warning: redundant redeclaration of `long long int gzoffset64(void*)' in same scope ../../src/zlib-1.2.5/zlib.h:1569: warning: previous declaration of `off64_t gzoffset64(void*)' ../../src/zlib-1.2.5/zlib.h:1586: warning: redundant redeclaration of `uLong adler32_combine64(uLong, uLong, long long int)' in same scope ../../src/zlib-1.2.5/zlib.h:1570: warning: previous declaration of `uLong adler32_combine64(uLong, uLong, off64_t)' ../../src/zlib-1.2.5/zlib.h:1587: warning: redundant redeclaration of `uLong crc32_combine64(uLong, uLong, long long int)' in same scope ../../src/zlib-1.2.5/zlib.h:1571: warning: previous declaration of `uLong crc32_combine64(uLong, uLong, off64_t)' Here some of the relavent lines from zlib.h referred to above: // This would be line 1558 of zlib.h /* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if * both are true, the application gets the *64 functions, and the regular * functions are changed to 64 bits) -- in case these are set on systems * without large file support, _LFS64_LARGEFILE must also be true */ #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); #endif #if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0 # define gzopen gzopen64 # define gzseek gzseek64 # define gztell gztell64 # define gzoffset gzoffset64 # define adler32_combine adler32_combine64 # define crc32_combine crc32_combine64 # ifdef _LARGEFILE64_SOURCE ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); # endif #else ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif // This would be line 1597 of zlib.h I'm not sure how to track this down further. I tried moving the include of zlib.h to the top and bottom of the includes list of the cpp file, but it made no difference. An excerpt of passing -E to g++ shows in part: extern int inflateInit2_ (z_streamp strm, int windowBits, const char *version, int stream_size); extern int inflateBackInit_ (z_streamp strm, int windowBits, unsigned char *window, const char *version, int stream_size); # 1566 "../../src/zlib-1.2.5/zlib.h" extern gzFile gzopen64 (const char *, const char *); extern off64_t gzseek64 (gzFile, off64_t, int); extern off64_t gztell64 (gzFile); extern off64_t gzoffset64 (gzFile); extern uLong adler32_combine64 (uLong, uLong, off64_t); extern uLong crc32_combine64 (uLong, uLong, off64_t); # 1582 "../../src/zlib-1.2.5/zlib.h" extern gzFile gzopen64 (const char *, const char *); extern long long gzseek64 (gzFile, long long, int); extern long long gztell64 (gzFile); extern long long gzoffset64 (gzFile); extern uLong adler32_combine64 (uLong, uLong, long long); extern uLong crc32_combine64 (uLong, uLong, long long); # 1600 "../../src/zlib-1.2.5/zlib.h" struct internal_state {int dummy;}; Not sure why lines 1566 and 1582 are coming out together in the CPP output, but hence the warning about duplicate declarations.

    Read the article

  • Where to put constant strings in C++: static class members or anonymous namespaces

    - by stone
    I need to define some constant strings that will be used only by one class. It looks like I have three options: Embed the strings directly into locations where they are used. Define them as private static constant members of the class: //A.h class A { private: static const std::string f1; static const std::string f2; static const std::string f3; }; //A.cpp const std::string f1 = "filename1"; const std::string f2 = "filename2"; const std::string f3 = "filename3"; //strings are used in this file Define them in an anonymous namespace in the cpp file: //A.cpp namespace { const std::string f1 = "filename1"; const std::string f2 = "filename2"; const std::string f3 = "filename3"; } //strings are used in this file Given these options, which one would you recommend and why? Thanks.

    Read the article

  • Trying to reduce the speed overhead of an almost-but-not-quite-int number class

    - by Fumiyo Eda
    I have implemented a C++ class which behaves very similarly to the standard int type. The difference is that it has an additional concept of "epsilon" which represents some tiny value that is much less than 1, but greater than 0. One way to think of it is as a very wide fixed point number with 32 MSBs (the integer parts), 32 LSBs (the epsilon parts) and a huge sea of zeros in between. The following class works, but introduces a ~2x speed penalty in the overall program. (The program includes code that has nothing to do with this class, so the actual speed penalty of this class is probably much greater than 2x.) I can't paste the code that is using this class, but I can say the following: +, -, +=, <, > and >= are the only heavily used operators. Use of setEpsilon() and getInt() is extremely rare. * is also rare, and does not even need to consider the epsilon values at all. Here is the class: #include <limits> struct int32Uepsilon { typedef int32Uepsilon Self; int32Uepsilon () { _value = 0; _eps = 0; } int32Uepsilon (const int &i) { _value = i; _eps = 0; } void setEpsilon() { _eps = 1; } Self operator+(const Self &rhs) const { Self result = *this; result._value += rhs._value; result._eps += rhs._eps; return result; } Self operator-(const Self &rhs) const { Self result = *this; result._value -= rhs._value; result._eps -= rhs._eps; return result; } Self operator-( ) const { Self result = *this; result._value = -result._value; result._eps = -result._eps; return result; } Self operator*(const Self &rhs) const { return this->getInt() * rhs.getInt(); } // XXX: discards epsilon bool operator<(const Self &rhs) const { return (_value < rhs._value) || (_value == rhs._value && _eps < rhs._eps); } bool operator>(const Self &rhs) const { return (_value > rhs._value) || (_value == rhs._value && _eps > rhs._eps); } bool operator>=(const Self &rhs) const { return (_value >= rhs._value) || (_value == rhs._value && _eps >= rhs._eps); } Self &operator+=(const Self &rhs) { this->_value += rhs._value; this->_eps += rhs._eps; return *this; } Self &operator-=(const Self &rhs) { this->_value -= rhs._value; this->_eps -= rhs._eps; return *this; } int getInt() const { return(_value); } private: int _value; int _eps; }; namespace std { template<> struct numeric_limits<int32Uepsilon> { static const bool is_signed = true; static int max() { return 2147483647; } } }; The code above works, but it is quite slow. Does anyone have any ideas on how to improve performance? There are a few hints/details I can give that might be helpful: 32 bits are definitely insufficient to hold both _value and _eps. In practice, up to 24 ~ 28 bits of _value are used and up to 20 bits of _eps are used. I could not measure a significant performance difference between using int32_t and int64_t, so memory overhead itself is probably not the problem here. Saturating addition/subtraction on _eps would be cool, but isn't really necessary. Note that the signs of _value and _eps are not necessarily the same! This broke my first attempt at speeding this class up. Inline assembly is no problem, so long as it works with GCC on a Core i7 system running Linux!

    Read the article

  • Memory leak in C++ program.

    - by lampshade
    What I have is a very crude linked list..THe problem for me is that I am getting a memory leak in the constructor or main. I think it is the constructor. I have not yet deleted the eventName varaible that I have allocated memory for. Could someone help please? :/ (This is not a homework question) class Event { private: char * eventName ; string userEvent; struct node { node(); node * nextByName; const char * eventName; }; node * headByName; public: Event(const char * eventName, const Date &myDate); Event(); virtual ~Event(); void insert(const char * eventName, const Date &myDate, const Time &myTime); void setEvent(); const char * const getEvent() const { return userEvent.c_str(); }; void displayByName(ostream& out) const; }; Event::Event(const char * eventName, const Date &myDate) : eventName(new char[strlen(eventName)+1]), headByName(NULL), userEvent("") { if (eventName) { size_t length = strlen(eventName) +1; strcpy_s(this->eventName, length, eventName); } else eventName = NULL; } Event::Event() : eventName(NULL), userEvent(NULL), headByName(NULL) { } Event::~Event() { node * temp_node = NULL; node * current_node = headByName; while ( current_node ) { temp_node = current_node->nextByName; delete current_node; current_node = temp_node; } } void Event::insert(const char * eventName, const Date &myDate, const Time &myTime) // when we insert we dont care about the time, just the name and the date { node * current_node = new node(); if ( headByName == NULL ) { headByName = current_node; headByName->eventName = eventName; } else { node * search_node = headByName; node * prev_node = NULL; while ( search_node != NULL ) { prev_node = search_node; search_node = search_node->nextByName; } if ( NULL == prev_node ) { headByName = current_node; } else { prev_node->nextByName = current_node; } current_node->nextByName = search_node; current_node->eventName = eventName ; } } void Event::displayByName(ostream& out) const { cout << "Scheduled Events are: " << endl << endl; node * current_node = headByName; while ( current_node ) { (char*)eventName = (char*)current_node->eventName; out << eventName << endl; current_node = current_node->nextByName; } } Event::node::node() : nextByName(NULL), eventName(NULL) { } void Event::setEvent() { cout << "\n\nEnter a new event! "; cin.getline((char*)userEvent.c_str(), 256); size_t length = strlen(userEvent.c_str()) +1; strcpy_s((char*)this->userEvent.c_str(), length, userEvent.c_str()); } /********************************************************************************* **********************************************************************************/ int main() { Date * dPtr = new Date("March", 21, 2010); // instaintiate our Date class object by allocating default date paramateres. Event * ePtr = new Event("First Day of Spring", *dPtr); Time * tPtr = new Time(10,12,"PM"); cout << "default Time is: " << tPtr << endl; cout << "default Date is: " << dPtr << endl; ePtr->insert("First Day of Spring",*dPtr, *tPtr); ePtr->insert("Valentines Day", Date("February",14,2010), *tPtr); ePtr->insert("New Years Day", Date("Janurary",1,2011), *tPtr); ePtr->insert("St. Patricks Day", Date("March",17,2010), *tPtr); ePtr->displayByName(cout); ePtr->setEvent(); const char * const theEvent = ePtr->getEvent(); dPtr->setDate(); ePtr->insert(theEvent, *dPtr, *tPtr); tPtr->setTime(); cout << "Your event: " << theEvent << " is scheduled for: " << endl << dPtr << "at" << tPtr; ePtr->displayByName(cout); delete tPtr; delete dPtr; delete ePtr; cin.ignore(); return 0; }

    Read the article

  • possible implementations of casting in c++

    - by lego69
    I have this snippet of the code in my header: class A { private: int player; public: A(int initPlayer = 0); A(const A&); A& operator=(const A&); ~A(); void foo() const; friend int operator==(const A& i, const A& member) const; }; implementation of the operator== int operator==(const A& i, const A& member) const{ if(i.player == member.player){ return 1; } return 0; } and I need casting for this part of my code: A *pa1 = new A(a2); assert(i == *pa1); i - is some int, which my function receives I receive an error non-member function, How can I fix it? thanks in advance

    Read the article

  • Error C2451: Illegal conditional expression of type 'UnaryOp<E1, Op>' in ostream - visual studio 9

    - by Steven Hill
    I am getting a repeated error with VS 9. The code compiles under GNU C++, but I want debug with the VS IDE. Any idea what could be causing this error. Error 13 error C2451: conditional expression of type 'UnaryOp' is illegal \Microsoft Visual Studio 9.0\VC\include\ostream 512 //unary constraint template class UnaryOp : public Constraint { public: const E1& e1; UnaryOp(const E1& _e1); bool Satisfiable() const; Bool SatisfiableAux() const; void Print (std::ostream& os) const; UnaryOp* clone () const; //operator bool () const { return true; } }; template std::ostream& operator<<(std::ostream& os, const UnaryOp& unop); UnaryOp code that uses ostream: template INLINE void UnaryOp::Print (std::ostream& os) const { os << *this; } template INLINE std::ostream& operator<<(std::ostream& os, const UnaryOp& unop) { return os << Op::name << unop.e1; } ostream line with error: _Myt& __CLR_OR_THIS_CALL put(_Elem _Ch) { // insert a character ios_base::iostate _State = ios_base::goodbit; const sentry _Ok(*this); 512 if (!_Ok) _State |= ios_base::badbit; else { // state okay, insert character _TRY_IO_BEGIN

    Read the article

  • Problem in Building mplsh-run in lshkit

    - by Yijinsei
    Hi guy, been trying out this for quite some time but I'm still unable to built mplsh-run from lshkit Not sure if this would help to explain my situation during the building process /tmp/cc17kth4.o: In function `lshkit::MultiProbeLshRecallTable::reset(lshkit::MultiProbeLshModel, unsigned int, double, double)': mplsh-run.cpp:(.text._ZN6lshkit24MultiProbeLshRecallTable5resetENS_18MultiProbeLshModelEjdd[lshkit::MultiProbeLshRecallTable::reset(lshkit::MultiProbeLshModel, unsigned int, double, double)]+0x230): undefined reference to `lshkit::MultiProbeLshModel::recall(double) const' /tmp/cc17kth4.o: In function `void lshkit::MultiProbeLshIndex<unsigned int>::query_recall<lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> > >(float const*, float, lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> >&) const': mplsh-run.cpp:(.text._ZNK6lshkit18MultiProbeLshIndexIjE12query_recallINS_11TopkScannerINS_6MatrixIfE8AccessorENS_6metric5l2sqrIfEEEEEEvPKffRT_[void lshkit::MultiProbeLshIndex<unsigned int>::query_recall<lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> > >(float const*, float, lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> >&) const]+0x2c4): undefined reference to `lshkit::MultiProbeLsh::genProbeSequence(float const*, std::vector<unsigned int, std::allocator<unsigned int> >&, unsigned int) const' /tmp/cc17kth4.o: In function `void lshkit::MultiProbeLshIndex<unsigned int>::query<lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> > >(float const*, unsigned int, lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> >&)': mplsh-run.cpp:(.text._ZN6lshkit18MultiProbeLshIndexIjE5queryINS_11TopkScannerINS_6MatrixIfE8AccessorENS_6metric5l2sqrIfEEEEEEvPKfjRT_[void lshkit::MultiProbeLshIndex<unsigned int>::query<lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> > >(float const*, unsigned int, lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> >&)]+0x4a): undefined reference to `lshkit::MultiProbeLsh::genProbeSequence(float const*, std::vector<unsigned int, std::allocator<unsigned int> >&, unsigned int) const' collect2: ld returned 1 exit status the command that i used to built mplsh-run is g++ -I./lshkit/include -L/usr/lib -lm -lgsl -lgslcblas -lboost_program_options-mt mplsh-run.cpp Do you guys have any clue on how I could solve this?

    Read the article

  • look up constants based on value.

    - by PLangeberg
    I have a 3rd party struct that is comprised of the following: [StructLayout(LayoutKind.Sequential, Size=1)] public struct BigBlueReasonCodes { public const int ABC_REASONCODE_DESCRIPTION01 = 1000; public const int ABC_REASONCODE_DESCRIPTION01 = 1005; public const int ABC_REASONCODE_DESCRIPTION01 = 1010; public const int DEF_REASONCODE_DESCRIPTION01 = 2001; public const int DEF_REASONCODE_DESCRIPTION01 = 2010; public const int DEF_REASONCODE_DESCRIPTION01 = 2013; public const int GHI_REASONCODE_DESCRIPTION01 = 3050; public const int GHI_REASONCODE_DESCRIPTION01 = 3051; public const int GHI_REASONCODE_DESCRIPTION01 = 3052; public const string JKL_REASONCODE_DESCRIPTION01 = "XYZ; public const string GHI_REASONCODE_DESCRIPTION01 = "ST"; static BigblueReasonCodes(); } I am trying to look up the reason description(the field name) based on the reason code(the value) so my class can do someting like: string failureReason = GetReasonDescription(reasoncode); Somethings of mention are some have int values and some have string values. I am only worried about the ones with int values. I also only want the ones that start with GHI_ if possible but not a big deal.

    Read the article

  • Problem with std::map and std::pair

    - by Tom
    Hi everyone. I have a small program I want to execute to test something #include <map> #include <iostream> using namespace std; struct _pos{ float xi; float xf; bool operator<(_pos& other){ return this->xi < other.xi; } }; struct _val{ float f; }; int main() { map<_pos,_val> m; struct _pos k1 = {0,10}; struct _pos k2 = {10,15}; struct _val v1 = {5.5}; struct _val v2 = {12.3}; m.insert(std::pair<_pos,_val>(k1,v1)); m.insert(std::pair<_pos,_val>(k2,v2)); return 0; } The problem is that when I try to compile it, I get the following error $ g++ m2.cpp -o mtest In file included from /usr/include/c++/4.4/bits/stl_tree.h:64, from /usr/include/c++/4.4/map:60, from m2.cpp:1: /usr/include/c++/4.4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = _pos]’: /usr/include/c++/4.4/bits/stl_tree.h:1170: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = _pos, _Val = std::pair<const _pos, _val>, _KeyOfValue = std::_Select1st<std::pair<const _pos, _val> >, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’ /usr/include/c++/4.4/bits/stl_map.h:500: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename _Alloc::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [with _Key = _pos, _Tp = _val, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’ m2.cpp:30: instantiated from here /usr/include/c++/4.4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’ m2.cpp:9: note: candidates are: bool _pos::operator<(_pos&) $ I thought that declaring the operator< on the key would solve the problem, but its still there. What could be wrong? Thanks in advance.

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >