I've got a problem with decltype
which doesn't work for vector
.
Vector Eq
is the same type as holder
and itemGrabbed
:
item* itemGrabbed;
item* holder;
std::vector<std::vector<item*>> Eq;
Everything is initialized, etc.
Eq
stores pointers to "inherited" objects - for example, objects from class itemAxe
.
Every item
class and inherited objects have the same constructor with this argument -> grapicsData
:
this->itemGrabbed = new std::remove_pointer<decltype(Eq[x][y]) > ::type{graphicsData};
this->itemGrabbed = new std::remove_pointer<decltype(holder) > ::type{graphicsData};
I guess I could just go with something like this:
item* temp=Eq[x][y];
this->itemGrabbed = new std::remove_pointer<decltype(temp) > ::type{graphicsData};
But I was wondering if it is possible to do it without temp
?
The problem is that the 2nd option works but I need to use the 1st one. All that because I need different assign and copy operators.
How can I achieve this?
decltype
is resolved by the compiler, at compilation time.
It does not (and cannot) take into account if a pointer to a base class refers to an instance of a derived class during runtime.
In your case:
holder
and temp
are both of type item*
, and so the compiler will resolve these 2 decltype
s usages in your question to item*
. After applying std::remove_pointer
they will become item
(and you'll be able to new
them).
As for Eq[x][y]
- it is actually if type item*&
(a reference to item*
) and will stay the same after applying std::remove_pointer
. Since you cannot use new
with a refernce type, you will get a compilation error.
MSVC for example issues this error for it:
error C2464: '_Ty': cannot use 'new' to allocate a reference
with
[
_Ty=item *&
]
Regarding type inference in runtime (asked about in comments):
C++ does not support full reflection, and so you cannot inspect the type of an object in runtime and use this type as is to create a new instance.
You will need to implement some code to do this heavy lifting, e.g. some kind of factory.
You can start with this post: Possible to instantiate object given its type in C++?.