2power10
2power10

Reputation: 1279

How can we create an instance in C++ by a string type name?

Suppose we only have a string

string typename = "int"

How can we get an instance by this typename.

Upvotes: 0

Views: 735

Answers (3)

Constantinius
Constantinius

Reputation: 35059

This is not directly supported in C++. You could use the Abstract Factory Pattern (see the Wikipedia article for it) and map the names of the class to the factory to create it.

Upvotes: 2

iammilind
iammilind

Reputation: 69988

In C++ you cannot have a type just from a string (or character array). Type must be declared at compile time.

[P.S. typename is a keyword in C++, so it cannot be used as variable.]

Upvotes: 4

jpalecek
jpalecek

Reputation: 47762

You cannot do this directly in C++.

The usual way it's done is registering all possible types in some factory that will create the data on the heap.

Upvotes: 1

Related Questions