Can i have a single template object based on the type given by user?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Rupal Shah
    New Member
    • Feb 2011
    • 1

    Can i have a single template object based on the type given by user?

    Like the functionality i want to achieve is as under: but it will not work. How can i achieve the same functionality?
    Code:
    # include <iostream.h>
    # include <conio.h>
    
    template <class T>
    class Test
    {
    	T a;
    	public:
    		void set()
    		{
    			cin>>a;
    		}
    		void display()
    		{
    			cout<<"A is"<<a<<endl;
    		}
    };
    
    int main()
    {
    	int choice;
    	cin>>choice;
    	if(choice == 1)
    	{
    		Test<int> obj;
    	}
    	else if(choice ==2)
    	{
    		Test<char> obj;
    
    	}
    	else
    	{
    		Test<float> obj;
    
    	}
    	obj.set();
    	obj.display();
    	return 0;
    }
  • hype261
    New Member
    • Apr 2010
    • 207

    #2
    I haven't tested this out, but I believe you can solve this problem using an interface class.

    Code:
    using namespace std;
    
    class Interface
    {
    public:
    virtual void set() = 0;
    virtual void display() = 0;
    };
    
    template<typename T>
    class Test : public Interface
    {
    public:
    virtual void set()
    {
    cin >> a;
    }
    
    virtual void display()
    {
    cout << a;
    }
    private:
    T a;
    };
    
    int main()
    {
    Interface * obj;
    
    int choice;
    cin >> choice;
    
    if(choice == 1) 
        { 
            obj = new Test<int>(); 
        } 
        else if(choice ==2) 
        { 
            obj = new Test<char>(); 
      
        } 
        else 
        { 
            obj = new Test<float>; 
      
        } 
        obj.set(); 
        obj.display(); 
        delete obj;
        return 0;
    }

    Comment

    Working...