Search Results

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

Page 1/136 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Force external function to be const

    - by vanna
    Here is my problem. I made a class with a member function declared as const that uses an external function that I cannot modify (declared in someone else's code) and that is not declared const. More precisely Someone else's code class B { public: void foo(); }; My code class A : public B { public: void bar() const { this->foo(); } }; I know that for member data we can force const-correctness by using mutable or const_cast. How can I 'hack' foo such that my compiler understands that I would like to use it as if it was const even if it is not declared in someone else's code ?

    Read the article

  • Modifying a const through a non-const pointer

    - by jasonline
    I'm a bit confused what happened in the following code: const int e = 2; int* w = ( int* ) &e; // (1) cast to remove const-ness *w = 5; // (2) cout << *w << endl; // (3) outputs 5 cout << e << endl; // (4) outputs 2 cout << "w = " << w << endl; // (5) w points to the address of e cout << "&e = " << &e << endl; In (1), w points to the address of e. In (2), that value was changed to 5. However, when the values of *w and e were displayed, their values are different. But if you print value of w pointer and &e, they have the same value/address. How come e still contained 2, even if it was changed to 5? Were they stored in a separate location? Or a temporary? But how come the value pointed by w is still the address of e?

    Read the article

  • Implicit conversion : const reference vs non-const reference vs non-reference

    - by Nawaz
    Consider this code, struct A {}; struct B { B(const A&) {} }; void f(B) { cout << "f()"<<endl; } void g(A &a) { cout << "g()" <<endl; f(a); //a is implicitly converted into B. } int main() { A a; g(a); } This compiles fine, runs fine. But if I change f(B) to f(B&), it doesn't compile. If I write f(const B&), it again compiles fine, runs fine. Why is the reason and rationale? Summary: void f(B); //okay void f(B&); //error void f(const B&); //okay I would like to hear reasons, rationale and reference(s) from the language specification, for each of these cases. Of course, the function signatures themselves are not incorrect. Rather A implicitly converts into B and const B&, but not into B&, and that causes the compilation error.

    Read the article

  • Double pointer const-correctness warnings in C

    - by Michael Koval
    You can obviously cast a pointer to non-const data to a a pointer of the same type to const data: int *x = NULL; int const *y = x; Adding additional const qualifiers to match the additional indirection should logically work the same way: int * *x = NULL; int *const *y = x; /* okay */ int const *const *z = y; /* warning */ Compiling this with GCC or Clang with the -Wall flag, however, results in the following warning: test.c:4:23: warning: initializing 'int const *const *' with an expression of type 'int *const *' discards qualifiers in nested pointer types int const *const *z = y; /* warning */ ^ ~ Why does adding an additional const qualifier "discard qualifiers in nested pointer types"?

    Read the article

  • What is the best Broadphase Interface for moving spheres?

    - by Molmasepic
    As of now I am working on optimizing the performance of the physics and collision, and as of now I am having some slowdowns on my other computers from my main. I have well over 3000 btSphereShape Rigidbodies and 2/3 of them do not move at all, but I am noticing(by the profile below) that collision is taking a bit of time to maneuver. Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls ms/call ms/call name 10.09 0.65 0.65 SphereTriangleDetector::collide(btVector3 const&, btVector3&, btVector3&, float&, float&, float) 7.61 1.14 0.49 btSphereTriangleCollisionAlgorithm::processCollision(btCollisionObject*, btCollisionObject*, btDispatcherInfo const&, btManifoldResult*) 5.59 1.50 0.36 btConvexTriangleCallback::processTriangle(btVector3*, int, int) 5.43 1.85 0.35 btQuantizedBvh::reportAabbOverlappingNodex(btNodeOverlapCallback*, btVector3 const&, btVector3 const&) const 4.97 2.17 0.32 btBvhTriangleMeshShape::processAllTriangles(btTriangleCallback*, btVector3 const&, btVector3 const&) const::MyNodeOverlapCallback::processNode(int, int) 4.19 2.44 0.27 btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGeneric(btRigidBody&, btRigidBody&, btSolverConstraint const&) 4.04 2.70 0.26 btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimit(btRigidBody&, btRigidBody&, btSolverConstraint const&) 3.73 2.94 0.24 Ogre::OctreeSceneManager::walkOctree(Ogre::OctreeCamera*, Ogre::RenderQueue*, Ogre::Octree*, Ogre::VisibleObjectsBoundsInfo*, bool, bool) 3.42 3.16 0.22 btTriangleShape::getVertex(int, btVector3&) const 2.48 3.32 0.16 Ogre::Frustum::isVisible(Ogre::AxisAlignedBox const&, Ogre::FrustumPlane*) const 2.33 3.47 0.15 1246357 0.00 0.00 Gorilla::Layer::setVisible(bool) 2.33 3.62 0.15 SphereTriangleDetector::getClosestPoints(btDiscreteCollisionDetectorInterface::ClosestPointInput const&, btDiscreteCollisionDetectorInterface::Result&, btIDebugDraw*, bool) 1.86 3.74 0.12 btCollisionDispatcher::findAlgorithm(btCollisionObject*, btCollisionObject*, btPersistentManifold*) 1.86 3.86 0.12 btSequentialImpulseConstraintSolver::setupContactConstraint(btSolverConstraint&, btCollisionObject*, btCollisionObject*, btManifoldPoint&, btContactSolverInfo const&, btVector3&, float&, float&, btVector3&, btVector3&) 1.71 3.97 0.11 btTriangleShape::getEdge(int, btVector3&, btVector3&) const 1.55 4.07 0.10 _Unwind_SjLj_Register 1.55 4.17 0.10 _Unwind_SjLj_Unregister 1.55 4.27 0.10 Ogre::D3D9HardwareVertexBuffer::updateBufferResources(char const*, Ogre::D3D9HardwareVertexBuffer::BufferResources*) 1.40 4.36 0.09 btManifoldResult::addContactPoint(btVector3 const&, btVector3 const&, float) 1.40 4.45 0.09 btSequentialImpulseConstraintSolver::setupFrictionConstraint(btSolverConstraint&, btVector3 const&, btRigidBody*, btRigidBody*, btManifoldPoint&, btVector3 const&, btVector3 const&, btCollisionObject*, btCollisionObject*, float, float, float) 1.24 4.53 0.08 btSequentialImpulseConstraintSolver::convertContact(btPersistentManifold*, btContactSolverInfo const&) 1.09 4.60 0.07 408760 0.00 0.00 Living::MapHide() 1.09 4.67 0.07 btSphereTriangleCollisionAlgorithm::~btSphereTriangleCollisionAlgorithm() 1.09 4.74 0.07 inflate_fast EDIT: Updated to show current Profile. I have only listed the functions using over 1% time from the many functions that are being used. Another thing is that each monster has a certain area that they stay in and are only active when a player is in said area. I was wondering if maybe there is a way to deactivate the non-active monsters from bullet(reactivating once in the area again) or maybe theres a different broadphase interface that I should use. The current BPI is btDbvtBroadphase. EDIT: Here is the Profile on the other computer(the top one is my main) Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls ms/call ms/call name 12.18 1.19 1.19 SphereTriangleDetector::collide(btVector3 const&, btVector3&, btVector3&, float&, float&, float) 6.76 1.85 0.66 btSphereTriangleCollisionAlgorithm::processCollision(btCollisionObject*, btCollisionObject*, btDispatcherInfo const&, btManifoldResult*) 5.83 2.42 0.57 btQuantizedBvh::reportAabbOverlappingNodex(btNodeOverlapCallback*, btVector3 const&, btVector3 const&) const 5.12 2.92 0.50 btConvexTriangleCallback::processTriangle(btVector3*, int, int) 4.61 3.37 0.45 btTriangleShape::getVertex(int, btVector3&) const 4.09 3.77 0.40 _Unwind_SjLj_Register 3.48 4.11 0.34 btBvhTriangleMeshShape::processAllTriangles(btTriangleCallback*, btVector3 const&, btVector3 const&) const::MyNodeOverlapCallback::processNode(int, int) 2.46 4.35 0.24 btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimit(btRigidBody&, btRigidBody&, btSolverConstraint const&) 2.15 4.56 0.21 _Unwind_SjLj_Unregister 2.15 4.77 0.21 SphereTriangleDetector::getClosestPoints(btDiscreteCollisionDetectorInterface::ClosestPointInput const&, btDiscreteCollisionDetectorInterface::Result&, btIDebugDraw*, bool) 1.84 4.95 0.18 btTriangleShape::getEdge(int, btVector3&, btVector3&) const 1.64 5.11 0.16 btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGeneric(btRigidBody&, btRigidBody&, btSolverConstraint const&) 1.54 5.26 0.15 btSequentialImpulseConstraintSolver::setupContactConstraint(btSolverConstraint&, btCollisionObject*, btCollisionObject*, btManifoldPoint&, btContactSolverInfo const&, btVector3&, float&, float&, btVector3&, btVector3&) 1.43 5.40 0.14 Ogre::D3D9HardwareVertexBuffer::updateBufferResources(char const*, Ogre::D3D9HardwareVertexBuffer::BufferResources*) 1.33 5.53 0.13 btManifoldResult::addContactPoint(btVector3 const&, btVector3 const&, float) 1.13 5.64 0.11 btRigidBody::predictIntegratedTransform(float, btTransform&) 1.13 5.75 0.11 btTriangleIndexVertexArray::getLockedReadOnlyVertexIndexBase(unsigned char const**, int&, PHY_ScalarType&, int&, unsigned char const**, int&, int&, PHY_ScalarType&, int) const 1.02 5.85 0.10 btSphereTriangleCollisionAlgorithm::CreateFunc::CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo&, btCollisionObject*, btCollisionObject*) 1.02 5.95 0.10 btSphereTriangleCollisionAlgorithm::btSphereTriangleCollisionAlgorithm(btPersistentManifold*, btCollisionAlgorithmConstructionInfo const&, btCollisionObject*, btCollisionObject*, bool) Edited same as other Profile.

    Read the article

  • Template inheritence c++

    - by Chris Condy
    I have made a template singleton class, I have also made a data structure that is templated. My question is; how do I make my templated data structure inherit from a singleton so you can only have one float type of this structure? I have tested both seperate and have found no problems. Code provided under... (That is the problem) template <class Type> class AbstractRManagers : public Singleton<AbstractRManagers<Type> > The problem is the code above doesn't work I get alot of errors. I cant get it to no matter what I do template a templated singleton class... I was asking for maybe advice or maybe if the code above is incorrect guidence? #ifndef SINGLETON_H #define SINGLETON_H template <class Type> class Singleton { public: virtual ~Singleton(); Singleton(); static Type* m_instance; }; template <class Type> Type* Singleton<Type>::m_instance = 0; #include "Singleton.cpp" #endif #ifndef SINGLETON_CPP #define SINGLETON_CPP #include "Singleton.h" template <class Type> Singleton<Type>::Singleton() { } template <class Type> Singleton<Type>::~Singleton() { } template <class Type> Type* Singleton<Type>::getInstance() { if(m_instance==nullptr) { m_instance = new Type; } return m_instance; } #endif #ifndef ABSTRACTRMANAGERS_H #define ABSTRACTRMANAGERS_H #include <vector> #include <map> #include <stack> #include "Singleton.h" template <class Type> class AbstractRManagers : public Singleton<AbstractRManagers<Type> > { public: virtual ~AbstractRManagers(); int insert(Type* type, std::string name); Type* remove(int i); Type* remove(std::string name); Type* get(int i); Type* getS(std::string name); int get(std::string name); int get(Type* i); bool check(std::string name); int resourceSize(); protected: private: std::vector<Type*> m_resources; std::map<std::string,int> m_map; std::stack<int> m_freePos; }; #include "AbstractRManagers.cpp" #endif #ifndef ABSTRACTRMANAGERS_CPP #define ABSTRACTRMANAGERS_CPP #include "AbstractRManagers.h" template <class Type> int AbstractRManagers<Type>::insert(Type* type, std::string name) { int i=0; if(!check(name)) { if(m_freePos.empty()) { m_resources.push_back(type); i = m_resources.size()-1; m_map[name] = i; } else { i = m_freePos.top(); m_freePos.pop(); m_resources[i] = type; m_map[name] = i; } } else i = -1; return i; } template <class Type> int AbstractRManagers<Type>::resourceSize() { return m_resources.size(); } template <class Type> bool AbstractRManagers<Type>::check(std::string name) { std::map<std::string,int>::iterator it; it = m_map.find(name); if(it==m_map.end()) return false; return true; } template <class Type> Type* AbstractRManagers<Type>::remove(std::string name) { Type* temp = m_resources[m_map[name]]; if(temp!=NULL) { std::map<std::string,int>::iterator it; it = m_map[name]; m_resources[m_map[name]] = NULL; m_freePos.push(m_map[name]); delete (*it).second; delete (*it).first; return temp; } return NULL; } template <class Type> Type* AbstractRManagers<Type>::remove(int i) { if((i < m_resources.size())&&(i > 0)) { Type* temp = m_resources[i]; m_resources[i] = NULL; m_freePos.push(i); std::map<std::string,int>::iterator it; for(it=m_map.begin();it!=m_map.end();it++) { if((*it).second == i) { delete (*it).second; delete (*it).first; return temp; } } return temp; } return NULL; } template <class Type> int AbstractRManagers<Type>::get(Type* i) { for(int i2=0;i2<m_resources.size();i2++) { if(i == m_resources[i2]) { return i2; } } return -1; } template <class Type> Type* AbstractRManagers<Type>::get(int i) { if((i < m_resources.size())&&(i >= 0)) { return m_resources[i]; } return NULL; } template <class Type> Type* AbstractRManagers<Type>::getS(std::string name) { return m_resources[m_map[name]]; } template <class Type> int AbstractRManagers<Type>::get(std::string name) { return m_map[name]; } template <class Type> AbstractRManagers<Type>::~AbstractRManagers() { } #endif #include "AbstractRManagers.h" struct b { float x; }; int main() { b* a = new b(); AbstractRManagers<b>::getInstance()->insert(a,"a"); return 0; } This program produces next errors when compiled : 1> main.cpp 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::stack<_Ty,_Container> &,const std::stack<_Ty,_Container> &)' : could not deduce template argument for 'const std::stack<_Ty,_Container> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\stack(166) : see declaration of 'std::operator <' 1> c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(124) : while compiling class template member function 'bool std::less<_Ty>::operator ()(const _Ty &,const _Ty &) const' 1> with 1> [ 1> _Ty=std::string 1> ] 1> c:\program files\microsoft visual studio 10.0\vc\include\map(71) : see reference to class template instantiation 'std::less<_Ty>' being compiled 1> with 1> [ 1> _Ty=std::string 1> ] 1> c:\program files\microsoft visual studio 10.0\vc\include\xtree(451) : see reference to class template instantiation 'std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,_Mfl>' being compiled 1> with 1> [ 1> _Kty=std::string, 1> _Ty=int, 1> _Pr=std::less<std::string>, 1> _Alloc=std::allocator<std::pair<const std::string,int>>, 1> _Mfl=false 1> ] 1> c:\program files\microsoft visual studio 10.0\vc\include\xtree(520) : see reference to class template instantiation 'std::_Tree_nod<_Traits>' being compiled 1> with 1> [ 1> _Traits=std::_Tmap_traits<std::string,int,std::less<std::string>,std::allocator<std::pair<const std::string,int>>,false> 1> ] 1> c:\program files\microsoft visual studio 10.0\vc\include\xtree(659) : see reference to class template instantiation 'std::_Tree_val<_Traits>' being compiled 1> with 1> [ 1> _Traits=std::_Tmap_traits<std::string,int,std::less<std::string>,std::allocator<std::pair<const std::string,int>>,false> 1> ] 1> c:\program files\microsoft visual studio 10.0\vc\include\map(81) : see reference to class template instantiation 'std::_Tree<_Traits>' being compiled 1> with 1> [ 1> _Traits=std::_Tmap_traits<std::string,int,std::less<std::string>,std::allocator<std::pair<const std::string,int>>,false> 1> ] 1> c:\users\chris\desktop\311\ideas\idea1\idea1\abstractrmanagers.h(28) : see reference to class template instantiation 'std::map<_Kty,_Ty>' being compiled 1> with 1> [ 1> _Kty=std::string, 1> _Ty=int 1> ] 1> c:\users\chris\desktop\311\ideas\idea1\idea1\abstractrmanagers.h(30) : see reference to class template instantiation 'AbstractRManagers<Type>' being compiled 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::stack<_Ty,_Container> &,const std::stack<_Ty,_Container> &)' : could not deduce template argument for 'const std::stack<_Ty,_Container> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\stack(166) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::stack<_Ty,_Container> &,const std::stack<_Ty,_Container> &)' : could not deduce template argument for 'const std::stack<_Ty,_Container> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\stack(166) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::deque<_Ty,_Alloc> &,const std::deque<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::deque<_Ty,_Alloc> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\deque(1725) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::deque<_Ty,_Alloc> &,const std::deque<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::deque<_Ty,_Alloc> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\deque(1725) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::deque<_Ty,_Alloc> &,const std::deque<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::deque<_Ty,_Alloc> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\deque(1725) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\xtree(1885) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\xtree(1885) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\xtree(1885) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::vector<_Ty,_Ax> &,const std::vector<_Ty,_Ax> &)' : could not deduce template argument for 'const std::vector<_Ty,_Ax> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\vector(1502) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::vector<_Ty,_Ax> &,const std::vector<_Ty,_Ax> &)' : could not deduce template argument for 'const std::vector<_Ty,_Ax> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\vector(1502) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::vector<_Ty,_Ax> &,const std::vector<_Ty,_Ax> &)' : could not deduce template argument for 'const std::vector<_Ty,_Ax> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\vector(1502) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::unique_ptr<_Ty,_Dx> &,const std::unique_ptr<_Ty2,_Dx2> &)' : could not deduce template argument for 'const std::unique_ptr<_Ty,_Dx> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\memory(2582) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::unique_ptr<_Ty,_Dx> &,const std::unique_ptr<_Ty2,_Dx2> &)' : could not deduce template argument for 'const std::unique_ptr<_Ty,_Dx> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\memory(2582) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::unique_ptr<_Ty,_Dx> &,const std::unique_ptr<_Ty2,_Dx2> &)' : could not deduce template argument for 'const std::unique_ptr<_Ty,_Dx> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\memory(2582) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(1356) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(1356) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(1356) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(1179) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(1179) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(1179) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\utility(318) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\utility(318) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const std::string' 1> c:\program files\microsoft visual studio 10.0\vc\include\utility(318) : see declaration of 'std::operator <' 1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2676: binary '<' : 'const std::string' does not define this operator or a conversion to a type acceptable to the predefined operator ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Read the article

  • Does it ever make sense to make a fundamental (non-pointer) parameter const?

    - by Scott Smith
    I recently had an exchange with another C++ developer about the following use of const: void Foo(const int bar); He felt that using const in this way was good practice. I argued that it does nothing for the caller of the function (since a copy of the argument was going to be passed, there is no additional guarantee of safety with regard to overwrite). In addition, doing this prevents the implementer of Foo from modifying their private copy of the argument. So, it both mandates and advertises an implementation detail. Not the end of the world, but certainly not something to be recommended as good practice. I'm curious as to what others think on this issue. Edit: OK, I didn't realize that const-ness of the arguments didn't factor into the signature of the function. So, it is possible to mark the arguments as const in the implementation (.cpp), and not in the header (.h) - and the compiler is fine with that. That being the case, I guess the policy should be the same for making local variables const. One could make the argument that having different looking signatures in the header and source file would confuse others (as it would have confused me). While I try to follow the Principle of Least Astonishment with whatever I write, I guess it's reasonable to expect developers to recognize this as legal and useful.

    Read the article

  • const TypedeffedIntPointer not equal to const int *

    - by dirk
    I have the following C++ code: typedef int* IntPtr; const int* cip = new int; const IntPtr ctip4 = cip; I compile this with Visual Studio 2008 and get the following error: error C2440: 'initializing' : cannot convert from 'const int *' to 'const IntPtr' Clearly my understanding of typedefs is not what is should be. The reason I'm asking, I'm storing a pointer type in a STL map. I have a function that returns a const pointer which I would like to use to search in the map (using map::find(const key_type&). Since const MyType* and const map<MyType*, somedata>::key_type is incompatible, I'm having problems. Regards Dirk

    Read the article

  • const member functions can call const member functions only?

    - by Abhi
    Hi all. Do const member functions call only const member functions? class Transmitter{ const static string msg; mutable int size; public: void xmit() const{ size = compute(); cout<<msg; } private: int compute() const{return 5;} }; string const Transmitter::msg = "beep"; int main(){ Transmitter t; t.xmit(); return EXIT_SUCCESS; } If i dont make compute() a const, then the compiler complains. Is it because since a const member function is not allowed to modify members, it wont allow any calls to non-consts since it would mean that the const member function would be 'indirectly' modifying the data members?

    Read the article

  • Higher order function « filter » in C++

    - by Red Hyena
    Hi all. I wanted to write a higher order function filter with C++. The code I have come up with so far is as follows: #include <iostream> #include <string> #include <functional> #include <algorithm> #include <vector> #include <list> #include <iterator> using namespace std; bool isOdd(int const i) { return i % 2 != 0; } template < template <class, class> class Container, class Predicate, class Allocator, class A > Container<A, Allocator> filter(Container<A, Allocator> const & container, Predicate const & pred) { Container<A, Allocator> filtered(container); container.erase(remove_if(filtered.begin(), filtered.end(), pred), filtered.end()); return filtered; } int main() { int const a[] = {23, 12, 78, 21, 97, 64}; vector<int const> const v(a, a + 6); vector<int const> const filtered = filter(v, isOdd); copy(filtered.begin(), filtered.end(), ostream_iterator<int const>(cout, " ")); } However on compiling this code, I get the following error messages that I am unable to understand and hence get rid of: /usr/include/c++/4.3/ext/new_allocator.h: In instantiation of ‘__gnu_cxx::new_allocator<const int>’: /usr/include/c++/4.3/bits/allocator.h:84: instantiated from ‘std::allocator<const int>’ /usr/include/c++/4.3/bits/stl_vector.h:75: instantiated from ‘std::_Vector_base<const int, std::allocator<const int> >’ /usr/include/c++/4.3/bits/stl_vector.h:176: instantiated from ‘std::vector<const int, std::allocator<const int> >’ Filter.cpp:29: instantiated from here /usr/include/c++/4.3/ext/new_allocator.h:82: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(const _Tp&) const [with _Tp = const int]’ cannot be overloaded /usr/include/c++/4.3/ext/new_allocator.h:79: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(_Tp&) const [with _Tp = const int]’ Filter.cpp: In function ‘Container<A, Allocator> filter(const Container<A, Allocator>&, const Predicate&) [with Container = std::vector, Predicate = bool ()(int), Allocator = std::allocator<const int>, A = const int]’: Filter.cpp:30: instantiated from here Filter.cpp:23: error: passing ‘const std::vector<const int, std::allocator<const int> >’ as ‘this’ argument of ‘__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> > std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, __gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = const int, _Alloc = std::allocator<const int>]’ discards qualifiers /usr/include/c++/4.3/bits/stl_algo.h: In function ‘_FIter std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = __gnu_cxx::__normal_iterator<const int*, std::vector<const int, std::allocator<const int> > >, _Predicate = bool (*)(int)]’: Filter.cpp:23: instantiated from ‘Container<A, Allocator> filter(const Container<A, Allocator>&, const Predicate&) [with Container = std::vector, Predicate = bool ()(int), Allocator = std::allocator<const int>, A = const int]’ Filter.cpp:30: instantiated from here /usr/include/c++/4.3/bits/stl_algo.h:821: error: assignment of read-only location ‘__result.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = const int*, _Container = std::vector<const int, std::allocator<const int> >]()’ /usr/include/c++/4.3/ext/new_allocator.h: In member function ‘void __gnu_cxx::new_allocator<_Tp>::deallocate(_Tp*, size_t) [with _Tp = const int]’: /usr/include/c++/4.3/bits/stl_vector.h:150: instantiated from ‘void std::_Vector_base<_Tp, _Alloc>::_M_deallocate(_Tp*, size_t) [with _Tp = const int, _Alloc = std::allocator<const int>]’ /usr/include/c++/4.3/bits/stl_vector.h:136: instantiated from ‘std::_Vector_base<_Tp, _Alloc>::~_Vector_base() [with _Tp = const int, _Alloc = std::allocator<const int>]’ /usr/include/c++/4.3/bits/stl_vector.h:286: instantiated from ‘std::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator, const _Alloc&) [with _InputIterator = const int*, _Tp = const int, _Alloc = std::allocator<const int>]’ Filter.cpp:29: instantiated from here /usr/include/c++/4.3/ext/new_allocator.h:98: error: invalid conversion from ‘const void*’ to ‘void*’ /usr/include/c++/4.3/ext/new_allocator.h:98: error: initializing argument 1 of ‘void operator delete(void*)’ /usr/include/c++/4.3/bits/stl_algobase.h: In function ‘_OI std::__copy_move_a(_II, _II, _OI) [with bool _IsMove = false, _II = const int*, _OI = const int*]’: /usr/include/c++/4.3/bits/stl_algobase.h:435: instantiated from ‘_OI std::__copy_move_a2(_II, _II, _OI) [with bool _IsMove = false, _II = __gnu_cxx::__normal_iterator<const int*, std::vector<const int, std::allocator<const int> > >, _OI = __gnu_cxx::__normal_iterator<const int*, std::vector<const int, std::allocator<const int> > >]’ /usr/include/c++/4.3/bits/stl_algobase.h:466: instantiated from ‘_OI std::copy(_II, _II, _OI) [with _II = __gnu_cxx::__normal_iterator<const int*, std::vector<const int, std::allocator<const int> > >, _OI = __gnu_cxx::__normal_iterator<const int*, std::vector<const int, std::allocator<const int> > >]’ /usr/include/c++/4.3/bits/vector.tcc:136: instantiated from ‘__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> > std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, __gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = const int, _Alloc = std::allocator<const int>]’ Filter.cpp:23: instantiated from ‘Container<A, Allocator> filter(const Container<A, Allocator>&, const Predicate&) [with Container = std::vector, Predicate = bool ()(int), Allocator = std::allocator<const int>, A = const int]’ Filter.cpp:30: instantiated from here /usr/include/c++/4.3/bits/stl_algobase.h:396: error: no matching function for call to ‘std::__copy_move<false, true, std::random_access_iterator_tag>::__copy_m(const int*&, const int*&, const int*&)’ Please tell me what I am doing wrong here and what is the correct way to achieve the kind of higher order polymorphism I want. Thanks.

    Read the article

  • A mysterious compilation error: cannot convert from 'const boost::shared_ptr<T>' to 'const boost::shared_ptr<T>'

    - by Stephane Rolland
    I wanted to protect the access to a log file that I use for multithreaded logging with boostlog library. I tried this stream class class ThreadSafeStream { public: template <typename TInput> const ThreadSafeStream& operator<< (const TInput &tInput) const { // some thread safe file access return *this; } }; using it this way (text_sink is a boostlog object): //... m_spSink.reset(new text_sink); text_sink::locked_backend_ptr pBackend = m_spSink->locked_backend(); const boost::shared_ptr< ThreadSafeStream >& spFileStream = boost::make_shared<ThreadSafeStream>(); pBackend->add_stream(spFileStream); // this causes the compilation error and I get this mysterious error: cannot convert from 'const boost::shared_ptr<T>' to 'const boost::shared_ptr<T>' the whole compile error: Log.cpp(79): error C2664: 'boost::log2_mt_nt5::sinks::basic_text_ostream_backend<CharT>::add_stream' : cannot convert parameter 1 from 'const boost::shared_ptr<T>' to 'const boost::shared_ptr<T> &' 1> with 1> [ 1> CharT=char 1> ] 1> and 1> [ 1> T=ThreadSafeStream 1> ] 1> and 1> [ 1> T=std::basic_ostream<char,std::char_traits<char>> 1> ] 1> Reason: cannot convert from 'const boost::shared_ptr<T>' to 'const boost::shared_ptr<T>' 1> with 1> [ 1> T=ThreadSafeStream 1> ] 1> and 1> [ 1> T=std::basic_ostream<char,std::char_traits<char>> 1> ] 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called I suspect that I am not well defining the operator<<()... but I don't find what is wrong.

    Read the article

  • Allow member to be const while still supporting operator= on the class

    - by LeopardSkinPillBoxHat
    I have several members in my class which are const and can therefore only be initialised via the initialiser list like so: class MyItemT { public: MyItemT(const MyPacketT& aMyPacket, const MyInfoT& aMyInfo) : mMyPacket(aMyPacket), mMyInfo(aMyInfo) { } private: const MyPacketT mMyPacket; const MyInfoT mMyInfo; }; My class can be used in some of our internally defined container classes (e.g. vectors), and these containers require that operator= is defined in the class. Of course, my operator= needs to do something like this: MyItemT& MyItemT::operator=(const MyItemT& other) { mMyPacket = other.mPacket; mMyInfo = other.mMyInfo; return *this; } which of course doesn't work because mMyPacket and mMyInfo are const members. Other than making these members non-const (which I don't want to do), any ideas about how I could fix this?

    Read the article

  • const return value and template instantiation

    - by Rimo
    From Herb Sutter's GotW #6 Return-by-value should normally be const for non-builtin return types. .... Note: Lakos (pg. 618) argues against returning const value, and notes that it is redundant for builtins anyway (for example, returning "const int"), which he notes may interfere with template instantiation. .... While Sutter seems to disagree on whether to return a const value or non-const value when returning an object of a non-built type by value with Lakos, he generally agrees that returning a const value of a built-in type (e.g const int) is not a good idea. While I understand why that is useless because the return value cannot be modified as it is an rvalue, I cannot find an example of how that might interfere with template instantiation. Please give me an example of how having a const qualifier for a return type might interfere with template instantiation.

    Read the article

  • g++ linker can't find const member function

    - by Max
    I have a Point class (with integer members x and y) that has a member function withinBounds that is declared like so: bool withinBounds(const Point&, const Point&) const; and defined like this: bool Point::withinBounds(const Point& TL, const Point& BR) const { if(x < TL.getX()) return false; if(x > BR.getX()) return false; if(y < TL.getY()) return false; if(y > BR.getY()) return false; // Success return true; } and then in another file, I call withinBounds like this: Point pos = currentPlayer->getPosition(); if(pos.withinBounds(topleft, bottomright)) { // code block } This compiles fine, but it fails to link. g++ gives me this error: /home/max/Desktop/Development/YARL/yarl/src/GameData.cpp:61: undefined reference to 'yarl::utility::Point::withinBounds(yarl::utility::Point const&, yarl::utility::Point const&)' When I make the function not const, it links fine. Anyone know the reason why? The linker error looks like it's looking for a non-const version of the function, but I don't know why it would.

    Read the article

  • Is it appropriate to set a value to a "const char *" in the header file

    - by sud
    I have seen people using 2 methods to declare and define char * Medhod-1: The header file has the below const char* COUNTRY_NAME_USA = "USA"; Medhod-2: The header file has the below declaration const char* COUNTRY_NAME_USA; The cpp file has the below defintion : const char* COUNTRY_NAME_USA = "USA"; Is method-2 wrong in some way ? What is the difference between the two ? I understand the difference between "const char * const var" , and "const char * var". If in the above methods if a "const char * const var" is declared and defined in the header as in method 1 will it make sense ?

    Read the article

  • Simplifying const Overloading?

    - by templatetypedef
    Hello all- I've been teaching a C++ programming class for many years now and one of the trickiest things to explain to students is const overloading. I commonly use the example of a vector-like class and its operator[] function: template <typename T> class Vector { public: T& operator[] (size_t index); const T& operator[] (size_t index) const; }; I have little to no trouble explaining why it is that two versions of the operator[] function are needed, but in trying to explain how to unify the two implementations together I often find myself wasting a lot of time with language arcana. The problem is that the only good, reliable way that I know how to implement one of these functions in terms of the other is with the const_cast/static_cast trick: template <typename T> const T& Vector<T>::operator[] (size_t index) const { /* ... your implementation here ... */ } template <typename T> T& Vector<T>::operator[] (size_t index) { return const_cast<T&>(static_cast<const Vector&>(*this)[index]); } The problem with this setup is that it's extremely tricky to explain and not at all intuitively obvious. When you explain it as "cast to const, then call the const version, then strip off constness" it's a little easier to understand, but the actual syntax is frightening,. Explaining what const_cast is, why it's appropriate here, and why it's almost universally inappropriate elsewhere usually takes me five to ten minutes of lecture time, and making sense of this whole expression often requires more effort than the difference between const T* and T* const. I feel that students need to know about const-overloading and how to do it without needlessly duplicating the code in the two functions, but this trick seems a bit excessive in an introductory C++ programming course. My question is this - is there a simpler way to implement const-overloaded functions in terms of one another? Or is there a simpler way of explaining this existing trick to students? Thanks so much!

    Read the article

  • C++: get const or non-const reference type from trait

    - by maciekp
    I am writing a functor F which takes function of type void (*func)(T) and func's argument arg. Then functor F calls func with arg. I would like F not to copy arg, just to pass it as reference. But then I cannot simply write "void F(void (*func)(T), T&)" because T could be a reference. So I am trying to write a trait, which allows to get proper reference type of T: T -> T& T& -> T& const T -> const T& const T& -> const T& I come up with something like this: template<typename T> struct type_op { typedef T& valid_ref_type; }; template<typename T> struct type_op<T&> { typedef typename type_op<T>::valid_ref_type valid_ref_type; }; template<typename T> struct type_op<const T> { typedef const T& valid_ref_type; }; template<typename T> struct type_op<const T&> { typedef const T& valid_ref_type; }; Which doesn't work for example for void a(int x) { std::cout << x << std::endl; } F(&a, 7); Giving error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’ in passing argument 2 of ‘void f(void (*)(T), typename type_op::valid_ref_type) [with T = int]’ How to get this trait to work?

    Read the article

  • Passing const CName as this argument discards qualifiers

    - by Geno Diaz
    I'm having trouble with passing a constant class through a function. // test the constructors auto CName nameOne("Robert", "Bresson"); const CName nameTwo = nameOne; auto CName nameThree; // display the contents of each newly-constructed object... // should see "Robert Bresson" cout << "nameOne = "; nameOne.WriteFullName(); cout << endl; // should see "Robert Bresson" again cout << "nameTwo = "; nameTwo.WriteFullName(); cout << endl; As soon as the compiler hits nameTwo.WriteFullName() I get the error of abandoning qualifiers. I know that the class is a constant however I can't figure out how to work around it. The function is in a header file written as so: void const WriteFullName(ostream& outstream = cout) { outstream << m_first << ' ' << m_last; } I receive this error when const is put in back of the function header main.cpp:(.text+0x51): undefined reference to CName::CName()' main.cpp:(.text+0x7c): undefined reference toCName::WriteFullName(std::basic_ostream &) const' main.cpp:(.text+0xbb): undefined reference to CName::WriteFullName(std::basic_ostream<char, std::char_traits<char> >&) const' main.cpp:(.text+0xf7): undefined reference toCName::WriteFullName(std::basic_ostream &) const' main.cpp:(.text+0x133): undefined reference to operator>>(std::basic_istream<char, std::char_traits<char> >&, CName&)' main.cpp:(.text+0x157): undefined reference tooperator<<(std::basic_ostream &, CName const&)' main.cpp:(.text+0x1f4): undefined reference to operator<<(std::basic_ostream<char, std::char_traits<char> >&, CName const&)' main.cpp:(.text+0x22b): undefined reference tooperator<<(std::basic_ostream &, CName const&)' main.cpp:(.text+0x25f): undefined reference to operator<<(std::basic_ostream<char, std::char_traits<char> >&, CName const&)' main.cpp:(.text+0x320): undefined reference tooperator<<(std::basic_ostream &, CName const&)' main.cpp:(.text+0x347): undefined reference to `operator(std::basic_istream &, CName&)'

    Read the article

  • How to provide stl like container with public const iterator and private non-const iterator?

    - by WilliamKF
    Hello, I am deriving a class privately from std::list and wish to provide public begin() and end() for const_iterator and private begin() and end() for just plain iterator. However, the compiler is seeing the private version and complaining that it is private instead of using the public const version. I understand that C++ will not overload on return type (in this case const_iterator and iterator) and thus it is choosing the non-const version since my object is not const. Short of casting my object to const before calling begin() or not overloading the name begin is there a way to accomplish this? I would think this is a known pattern that folks have solved before and would like to follow suit as to how this is typically solved. class myObject; class myContainer : private std::list<myObject> { public: typedef std::list<myObject>::const_iterator myContainer::const_iterator; private: typedef std::list<myObject>::iterator myContainer::iterator; public: myContainer::const_iterator begin() const { return std::list<myObject>::begin(); } myContainer::const_iterator end() const { return std::list<myObject>::end(); } private: myContainer::iterator begin() { return std::list<myObject>::begin(); } myContainer::iterator end() { return std::list<myObject>::end(); } }; void myFunction(myContainer &container) { myContainer::const_iterator aItr = container.begin(); myContainer::const_iterator aEndItr = container.end(); for (; aItr != aEndItr; ++aItr) { const myObject &item = *aItr; // Do something const on container's contents. } } The error from the compiler is something like this: ../../src/example.h:447: error: `std::_List_iterator<myObject> myContainer::begin()' is private caller.cpp:2393: error: within this context ../../src/example.h:450: error: `std::_List_iterator<myObject> myContainer::end()' is private caller.cpp:2394: error: within this context Thanks. -William

    Read the article

  • C function const multidimensional-array argument strange warning

    - by rogi
    Ehllo, I'm getting some strange warning about this code: typedef double mat4[4][4]; void mprod4(mat4 r, const mat4 a, const mat4 b) { /* yes, function is empty */ } int main() { mat4 mr, ma, mb; mprod4(mr, ma, mb); } gcc output as follows: $ gcc -o test test.c test.c: In function 'main': test.c:13: warning: passing argument 2 of 'mprod4' from incompatible pointer type test.c:4: note: expected 'const double (*)[4]' but argument is of type 'double (*)[4]' test.c:13: warning: passing argument 3 of 'mprod4' from incompatible pointer type test.c:4: note: expected 'const double ()[4]' but argument is of type 'double ()[4]' defining the function as: void mprod4(mat4 r, mat4 a, mat4 b) { } OR defining matrices at main as: mat4 mr; const mat4 ma; const mat4 mb; OR calling teh function in main as: mprod4(mr, (const double(*)[4])ma, (const double(*)[4])mb); OR even defining mat4 as: typedef double mat4[16]; make teh warning go away. Wat is happening here? Am I doing something invalid? gcc version is 4.4.3 if relevant. Thanks for your attention.

    Read the article

  • Detecting const-ness of nested type

    - by Channel72
    Normally, if I need to detect whether a type is const I just use boost::is_const. However, I ran into trouble when trying to detect the const-ness of a nested type. Consider the following traits template, which is specialized for const types: template <class T> struct traits { typedef T& reference; }; template <class T> struct traits<const T> { typedef T const& reference; }; The problem is that boost::is_const doesn't seem to detect that traits<const T>::reference is a const type. For example: std::cout << std::boolalpha; std::cout << boost::is_const<traits<int>::reference>::value << " "; std::cout << boost::is_const<traits<const int>::reference>::value << std::endl; This outputs: false false Why doesn't it output false true?

    Read the article

  • Returning a C++ reference in a const member functionasses

    - by Chris Kaminski
    A have a class hierarchy that looks somethign like this: class AbstractDataType { public: virtual int getInfo() = 0; }; class DataType: public AbstractDataType { public: virtual int getInfo() { }; } class Accessor { DataType data; public: const AbstractDataType& getData() const { return(data); } } Well, GCC 4.4 reports: In member function ‘const AbstractDataType& Accessor::getData() const’: error: invalid initialization of reference of type ‘const AbstractDataType&’ from expression of type ‘const DataType’ Where am I going wrong - is this a case where I MUST use a pointer?

    Read the article

  • C++: Why does gcc prefer non-const over const when accessing operator[]?

    - by JonasW
    This question might be more appropriately asked regarding C++ in general, but as I am using gcc on linux that's the context. Consider the following program: #include <iostream> #include <map> #include <string> using namespace std; template <typename TKey, typename TValue> class Dictionary{ public: map<TKey, TValue> internal; TValue & operator[](TKey const & key) { cout << "operator[] with key " << key << " called " << endl; return internal[key]; } TValue const & operator[](TKey const & key) const { cout << "operator[] const with key " << key << " called " << endl; return internal.at(key); } }; int main(int argc, char* argv[]) { Dictionary<string, string> dict; dict["1"] = "one"; cout << "first one: " << dict["1"] << endl; return 0; } When executing the program, the output is: operator[] with key 1 called operator[] with key 1 called first one: one What I would like is to have the compiler choose the operator[]const method instead in the second call. The reason is that without having used dict["1"] before, the call to operator[] causes the internal map to create the data that does not exist, even if the only thing I wanted was to do some debugging output, which of course is a fatal application error. The behaviour I am looking for would be something like the C# index operator which has a get and a set operation and where you could throw an exception if the getter tries to access something that doesn't exist: class MyDictionary<TKey, TVal> { private Dictionary<TKey, TVal> dict = new Dictionary<TKey, TVal>(); public TVal this[TKey idx] { get { if(!dict.ContainsKey(idx)) throw KeyNotFoundException("..."); return dict[idx]; } set { dict[idx] = value; } } } Thus, I wonder why the gcc prefers the non-const call over the const call when non-const access is not required.

    Read the article

  • Cast vector<T> to vector<const T>

    - by user345386
    I have a member variable of type vector (where is T is a custom class, but it could be int as well.) I have a function from which I want to return a pointer to this vector, but I don't want the caller to be able to change the vector or it's items. So I want the return type to be const vector* None of the casting methods I tried worked. The compiler keeps complaining that T is not compatible with const T. Here's some code that demonstrates the gist of what I'm trying to do; vector<int> a; const vector<const int>* b = (const vector<const int>* ) (&a); This code doesn't compile for me. Thanks in advance!

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >