On Jan 20, 12:09 am, zraj...@gmail.com wrote:
Hi,
I have the following code.
struct Object
{
int m_id;
void setId(int const id)
{
m_id = id;
}
};
// version 1
template < class T >
void resetId(T &obj, int const id)
{
obj.setId(id);
}
// version 2
template < class T >
void resetId(boost::shared_ptr < T const &obj, int const id)
void resetId(boost::shared_ptr< T >& sp, int const id)
{
obj->setId(id);
sp->setId(id);
>
}
int main()
{
Object obj1;
resetId(obj1, 1); // calls version 1
boost::shared_ptr < Object obj2;
resetId(obj2, 2); // This calls version 1 too
boost::shared_ptr< Object bsp(new Object);
resetId(bsp, 2);
note: don't construct a temporary, see boost's notes on shared_ptr
>
}
This is with GCC 3.2.3...
How can I make sure that the call "resetId(obj2, 2)" calls version 2
that is overloaded for shared_ptr objects.
Any reason you aren't using constructors? After all, the compiler will
generate a default ctor if you don't. And you can supply as many
constructors as you need. Do not ignore ctors in C++, including copy
constructors. In fact, i find its *very* rare that i don't provide
ctors + init list for types. They save a lot of hardship and greatly
enhance the code.
struct Object
{
Object() : m_id(0) { } // default ctor
Object(const int id) : m_id(id) { } // parametized ctor
resetId(int const id) { m_id = id; }
private:
int m_id;
};
int main()
{
Object obj(1);
}