6

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?

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • 1
    It seems like the short answer is that C++ does not support reflection, but I bet there's some pretty absurd workarounds you could pump out for interviewer entertainment. Take a look at http://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-a-c-application for reflection – Catalyst Jul 07 '15 at 08:45
  • I think it is still interesting if someone can give a "simple" possible solution for this question. – coincoin Jul 07 '15 at 08:50

3 Answers3

4

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.
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

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();

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
0

I recently thought about this too. I came up with a class member that is casted at the start of each method based on some string and if/else block.

void* data;
string cast; //set cast with some method, could also be enum.
//make methods and/or overloads with cast blocks
jiggunjer
  • 1,905
  • 1
  • 19
  • 18