Reputation: 17183
I have a template class template <typename T> class SomeClass
. It has a member T* data[10]
, and a method:
void add(const T& item){
data[indexToInsert++] = item;
}
In main()
, there is the following code:
SomeClass<int> container;
container.add(10);
On the second line, I get this error:
invalid conversion from int to int*
I don't understand why I get this error. The integer 10
is passed as const reference to add()
. Then, as a const reference, it's assigned to an array of pointers.
Either some of my assumptions are wrong (for example, is T* data[10]
actually an array of pointers?), or something that I think should work doesn't.
Please explain the technical reasons to why this fails and how to fix it.
Upvotes: 0
Views: 1249
Reputation: 15524
The member data
is declared as an array of T*
, i.e. an array of pointers as you said yourself.
T* data[10] // 'data' is an array of T*.
To declare an array of T
use:
T data[10]; // 'data' is an array of T.
You get the error because you are trying to assign an int
to an array element of type int*
. Signed integers are not implicitly convertible to addresses/pointers.
Also remember that a reference is basically an alias of an object i.e. it behaves as if you pass the object itself but with reference semantics. You can not assign a reference to a pointer, but you can assign a reference to an object.
int i = 5;
int& r = i; // Reference to 'i';
int* p = &i; // Pointer to 'i'.
std::cout << r << std::endl; // Outputs '5'.
std::cout << p << std::endl; // Outputs the address of 'i'.
Upvotes: 2
Reputation: 395
You hit the nail on the head: T* data[10] is an array of pointers.
Change your member array to:
T data[10];
...and you'll be fine.
Upvotes: 0