Templates, overloading & const

Z

zrajbun

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)
{
obj->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
}

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.
 
S

Salt_Peter

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 said:
{
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);
}
 
Z

zrajbun

The code is just an example piece from the actual problem. I don't
have the luxury of constructors that take just the ID, because the
code for class Object is generated from a kind of IDL where there is
no constructor that just sets the ID value and ID is a member that I
dont define, but generated by the IDL compiler automatically. Hope
that helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,967
Members
47,516
Latest member
TobiasAxf

Latest Threads

Top