returning constant reference of element from a template

C

cuneyt

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
 
V

Victor Bazarov

cuneyt said:
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
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top