Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puzzle: To escape the check of typeid

Tags:

c++

typeid

I formed a nice interview question by chance. :)

template<typename T>
bool foo (T obj)
{
  if(typeid(T) == typeid(obj))
    return false;
  return true;  // <-- execute this
}

You have to call (only above mentioned) foo() in such a way that it returns true. Conditions are,

  1. Cannot edit or overload foo() or typeid
  2. No platform specific hacks allowed
  3. No #define allowed
like image 993
iammilind Avatar asked May 18 '11 09:05

iammilind


2 Answers

#include <cassert>

struct B { virtual ~B() {} };

int main()
{
    struct : B {} x;
    assert(foo<B&>(x));
}

Action is over there.

like image 183
Alexandre C. Avatar answered Nov 01 '22 01:11

Alexandre C.


int main ()
{
  typedef char C[1];
  foo<C>(0);  // returns true;
}

Refer this question to know the explanation of this answer and root of this question.

like image 45
iammilind Avatar answered Nov 01 '22 01:11

iammilind