nsvir
nsvir

Reputation: 8961

Throw exception when this instanced as const

I've got an assignment operator in my class

template<typename T>
T&   array<T>::operator[](int value);

this method can be used like a const and none const method:

array[100] = value; // None const cause if size > array.size(): resize it!

std::cout << array[0]; // const

If my object is instanced as a const object and ask me to resize it I must throw an exception.

How can I know that I am instanced as a const object ?

Upvotes: 0

Views: 98

Answers (4)

Konrad Talik
Konrad Talik

Reputation: 916

this method can be used like a const and none const method:

You're wrong here. To use [] as a const method you should overload it with const definition of the method (const {/*definition*/}).

Additionally you should make your int argument (or unsigned the best) also a const variable.

That means declaring following headers:

template<typename T>
T&   array<T>::operator[](const int value);       // Read-write
template<typename T>
T&   array<T>::operator[](const int value) const; // Read

Upvotes: 0

Wojtek Surowka
Wojtek Surowka

Reputation: 21003

I understand that you don't want just to have const and non-const version of your operator, but what you want is to know if the value returned by the operator is modified or not, and if it is used in a context where it is not modified, exception should be thrown for out-of-range index. If so, I do not think it is possible in C++.

Upvotes: -1

Sean
Sean

Reputation: 62512

Just provide a const version:

template<typename T>
const T&   array<T>::operator[](int value)const
{
  // throw exception
}

The const version will be called when your instance is constant, the non-const will be called when it's not constant.

Upvotes: 2

Adriano Repetti
Adriano Repetti

Reputation: 67118

Just add a second version of your [] operator with a const modifier, it'll be called for const objects.

This one for non const objects:

template<typename T>
T& array<T>::operator[](int value);

And this one will be called for const objects:

template<typename T>
T& array<T>::operator[](int value) const;

That said don't forget that const in C++ is pretty weak and a simple const_cast will bypass it so you may think about another protection too.

Edit: note (see comments) that according to what you're doing you may declare return type of const function as const T&. It may be your case or not (if collection is const then its elements have to be const too?).

Upvotes: 2

Related Questions