Rishabh Arora
Rishabh Arora

Reputation: 9

Variables that can be used as data types.

Is there any way in C++ through I can store the data types in the program like (int, char, std::string etc.) in some particular kind of variable and then use that variable instead, in place of the regular data types (for eg: to declare other variables)?

For eg:-

T = some-function("int")
now std::vector < T > is equivalent to std::vector <int> ? 

Upvotes: 0

Views: 133

Answers (3)

Ap31
Ap31

Reputation: 3324

C++ is a statically typed language, which implies that types pretty much do not exist in the runtime. Function return type is completely defined by parameter types (const char*) and cannot depend on parameter values ("int").

Computational flow can be influenced by types, e.g. via overload - but not vice versa. As a result, you cannot "compute" a type by calling some function.

Instead you can use templates/decltype/auto to produce complex and context-dependent types in compile time, or use polymorphic types.

Polymorphic types do indeed have runtime-defined behavior: you can make your some-function return an abstract factory, and then use that factory to produce your objects - their concrete type would be unknown at compile time. Of course, you would still need to instantiate the vector with some static type - usually a pointer to the generic class (AbstractType*).

The fact that you mention int, char and std::string hints that you probably don't want the whole polymorphic hierarchy and can manage with static types.

Here are some templates to determine the result type of calling a function. Notice that the function is not even called - again, the return type only depends on parameter types, not some computation.

Upvotes: 0

Daniel Jour
Daniel Jour

Reputation: 16156

You can alias types (give them another name) with the using keyword:

using vi = std:: vector<int>; // I recommend against such short names
// ...
vi some_vector_with_integers;

Of course this happens purely at compile time.

Wrapping such declarations in templates allows for compile programming:

template<int N>
using X = std::conditional<(N > 42), int, double>:: type;

Upvotes: 0

skypjack
skypjack

Reputation: 50550

You can use templates and decltype.
A minimal, working example based on your snippet:

#include<vector>

template<typename T>
T some_function() { return {}; }

int main() {
    // t has type int
    auto t = some_function<int>();
    // vec has type std::vector<int> now
    std::vector<decltype(t)> vec;
}

Upvotes: 4

Related Questions