template won't compile when used with bool

G

Greg

this template won't compile when used with bool, the erorr is
"invalid initialization of non const reference"

template < typename T >
class Vec : public std::vector< T > {
public:
Vec() { }
Vec( int s ) : std::vector<T>(s) { }
T& operator[](int i) { return this -> at(i); }
// <- this line
const T& operator[](int i) const { return this -> at(i); }
};

Vec<bool> b;
 
M

mlimber

Greg said:
this template won't compile when used with bool, the erorr is
"invalid initialization of non const reference"

template < typename T >
class Vec : public std::vector< T > {
public:
Vec() { }
Vec( int s ) : std::vector<T>(s) { }
T& operator[](int i) { return this -> at(i); }
// <- this line
const T& operator[](int i) const { return this -> at(i); }
};

Vec<bool> b;

Don't inherit from a std classes that are not meant to be inherited
from. Prefer composition when you can (cf.
http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.3).

Anyway, it's likely breaking because the standard library provides a
specialization for std::vector<bool>.

Cheers! --M
 
R

Ron Natalie

Greg said:
this template won't compile when used with bool, the erorr is
"invalid initialization of non const reference"

template < typename T >
class Vec : public std::vector< T > {
public:
Vec() { }
Vec( int s ) : std::vector<T>(s) { }
T& operator[](int i) { return this -> at(i); }
// <- this line
const T& operator[](int i) const { return this -> at(i); }
};

Vec<bool> b;
std::vector<bool> is specialized and the operator[] and at()
functions do not return bool&.
 
G

Greg

I only started using this template for debugging purposes, I don't need
it for the time being.
 

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
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top