By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,128 Members | 1,224 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,128 IT Pros & Developers. It's quick & easy.

returning constant reference of element from a template

P: n/a
Hi all:

I have defined the template

template<class T>
class CGroup
private:
int nSize;
public:
std::deque<T> c;
};

I would like to add a function that returns an element in the deque
with a given index (for other reasons, I chose not to use vector).
Below is my first attempt:

template<class T>
inline T& CGroup<T>::getElement( int nIndex ) const
{
if( (nIndex < 0) || (nIndex > c.size() ) ) {
std::cerr << "Index = " << nIndex << " out of range in
getElement()!" <<
std::endl;
exit(1);
}
return *(c.begin()+nIndex);
}

The compiler gave the error: return' : cannot convert from 'const
struct TFrame' to 'struct TFrame &'. How can I specify that the
reference to T that is being returned is a constant reference?

Thanks,

Cuneyt

Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
cuneyt wrote:
I have defined the template

template<class T>
class CGroup
private:
int nSize;
public:
std::deque<T> c;
};

I would like to add a function that returns an element in the deque
with a given index (for other reasons, I chose not to use vector).
Below is my first attempt:

template<class T>
inline T& CGroup<T>::getElement( int nIndex ) const
template<class T>
inline T const& CGroup<T>::getElement( int nIndex ) const

That should do it...
{
if( (nIndex < 0) || (nIndex > c.size() ) ) {
std::cerr << "Index = " << nIndex << " out of range in
getElement()!" <<
std::endl;
exit(1);
}
return *(c.begin()+nIndex);
}

The compiler gave the error: return' : cannot convert from 'const
struct TFrame' to 'struct TFrame &'. How can I specify that the
reference to T that is being returned is a constant reference?


See above

V
Jul 23 '05 #2

P: n/a
Yes, it worked.

Thanks a lot!

Cuneyt

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.