Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to identify the type of a variable

Tags:

c++

types

Given a variable taken from a vector, is there a way to identify the type.

Note that I already know the type of member and can specify it in the call to a template. This is a specific vector that allows a push_back() of particular types of variables.

For example, we have a class that allows a vector operation.

auto data = member().back(); // gets the last entry in the member vector

Using a template, I want to create a new entry of the type

dataType newdata;
member().push_back(newdata)

Is there a way of identifying what dataType is, given the result of the back() operation? If there is, I can create a Template, and retrieve the type by passing in the member indicator.

If not, I would have to pass in the type specifically in order to define

::base::dataArea newdata;
like image 748
sabbahillel Avatar asked Mar 17 '23 20:03

sabbahillel


2 Answers

You can just use typename std::remove_reference<decltype( member().back() )>::type if you really want to be clever. But instead you should use typename V::value_type, where V is the type of the vector accessed via member. See e.g. the docs at cppreference: it's often a good idea to consult the relevant documentation.

like image 88
Cheers and hth. - Alf Avatar answered Mar 19 '23 09:03

Cheers and hth. - Alf


Simple solution: member().resize(member().size()+1).

You cannot reason about unknown datatypes in general, so there is very little what you can do with them. You can't blindly assume they have a member .foo() for instance. You might reasonably assume that the type has a default, copy and/or move constructor, and then you often don't need to spell out the type either - as shown in the .resize() call.

like image 44
MSalters Avatar answered Mar 19 '23 10:03

MSalters