Once I was asked a question during the interview.
Hence I have a function void f(std::string)
, and I call a function as this f("int")
. So that my function must create a local int x
in its body. Is there a way to get the type from const char*
. I know that boost::mpl::vector
does solve this kind of problem. Can anyone tell me the technique?
The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.
The std::string type is the main string datatype in standard C++ since 1998, but it was not always part of C++. From C, C++ inherited the convention of using null-terminated strings that are handled by a pointer to their first element, and a library of functions that manipulate such strings.
To get the datatype of variable, use typeid(x). name() of typeinfo library. It returns the type name of the variable as a string.
string at() in C++std::string::at can be used to extract characters by characters from a given string. Syntax 2: const char& string::at (size_type idx) const idx : index number Both forms return the character that has the index idx (the first character has index 0).
If user-defined types are supposed to be supported, then it's not possible without an explicit mapping provided. But for just built-in types, it can be done. You could implement a parser for type definitions and combine it with function templates, constructing the type iteratively. Something like this:
template <class T>
void parseType(std::string type)
{
std::string spec = extractOneSpecifierFrom(type);
if (spec == "[]") {
parseType<T[]>(type);
} else if (spec == "*") {
parseType<T*>(type);
} else if (spec == "const") {
parseType<const T>(type);
} // ... etc.
}
My impression of this question is:
Creating a local int is done during the compile phase.
The argument s to f(std::string s) is runtime data.
So unless you are inspecting the string during runtime and selecting a block, or a predefined template, with an int, like
if ( s == "int" ){
// declare int
int i;
}
there is no reasonable way to do this.
To have object code with every possible data type available during compilation seems to me to go against the spirit of the question.
Now, with languages that has proper reflection the solution is mostly trivial. Object intObject = Class.forName(s).newInstance();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With