JOIN
Get Time
forums   
Search | Watch Thread  |  My Post History  |  My Watches  |  User Settings
View: Flat (newest first)  | Threaded  | Tree
Previous Thread  |  Next Thread
<< PREV    [ 1 2 ]
Re: A challenge problem (response to post by bmerry) | Reply
I have the following solution to the interesting challenge problem
#include <iostream>
#include <typeinfo> 
using namespace std; 
 
template<typename t> 
class Base
{
   public:
     void foo() {
       if(strcmp(typeid(*this).name(), typeid(t).name()) == 0)
           (static_cast<t*>(this)) -> foo(); 
       else 
           cout<<"base::foo()"<<endl;             
     } 
};
 
class Derv : public Base<Derv> 
{
  public: 
     void foo() {cout<<"derv::foo"<<endl;}
}; 
 
 
int main(int argc, char argv[])
{ 
    Derv * d = new Derv(); 
    d->foo(); //calls the derv version 
    
    //polymorphisim 
    Base<Derv> * bPtr = new Derv(); 
    bPtr->foo(); //calls derv version 
    
}
Re: A challenge problem (response to post by sanjit_rath) | Reply
See my clarification: you've changed the main method, which isn't the idea of the problem. I also suspect this code will do the strcmp at run-time, since typeid uses run-time type information (RTTI), and so in the "polymorphic" case it will be less efficient than a virtual function even though the type is known at compile time.
<< PREV    [ 1 2 ]

RSS