how to create class object in If-condition and use function in same code?

Is it possible that I give the template a type according to user choice, and then call the functions of that object???? if yes then please tell me how...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  int main()
{  
    int choice;
w:  cout<<"What type of DATA do you want to store in list?"<<endl;
    cout<<"press 1 for char \npress 2 for int \npress 3 for float"<<endl;
    choice=getch();
    if(choice==49)
    {dllist<char> obj;} 
    else if(choice==50)
    {dllist<int> obj;}
    else if(choice==51)
    {dllist<float> obj;}
    else
    { system("CLS"); 
	cout<<"wrong selection! TRY AGAIN..."<<endl; 
    goto w; 
	}
	system("CLS");
x:	cout<<"press 1 to count nodes\npress 2 to display List\npress 3 for other operations"<<endl;
	choice=getch();
    if(choice==49)
    {obj.countnode();} 
    else if(choice==50)
    {obj.display();}
    else if(choice==51)
    {dllist<float> obj;}
    else
    { system("CLS"); 
	cout<<"wrong selection! TRY AGAIN..."<<endl;
	goto x;}
Template arguments are handled at compile time. You can't change it at compile time.
mean... its not possible to take choice from user about template type?
by any way?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <vector>

template < typename CONTAINER > void add_to_list( CONTAINER& cntr )
{
    typename CONTAINER::value_type value ;
    std::cout << "enter value: " ;
    std::cin >> value ;
    cntr.push_back(value) ;
}

template < typename CONTAINER > void display_list( const CONTAINER& cntr )
{
    for( const auto& value : cntr ) std::cout << value << ' ' ;
    std::cout << '\n' ;
}

// etc

template < typename DATA > void do_things_with_list()
{
    std::vector<DATA> cntr ;

    int choice = 1 ;
    while( choice != 3 )
    {
        std::cout << " press 1 to add items\npress 2 to display list\npress 3 to quit\n" ;
        std::cin >> choice ;

        switch(choice)
        {
            case 1 : add_to_list(cntr) ; break ;
            case 2 : display_list(cntr) ; break ;
            case 3 : break ;
            default: std::cerr << "invalid choice\n" ;
        }
    }
}

int main()
{
    std::cout << "What type of DATA do you want to store in list?\n"
                 "press 1 for char \npress 2 for int \npress 3 for double\n" ;

    int choice ;
    std::cin >> choice ;

    switch(choice)
    {
        case 1 : do_things_with_list<char>() ; break ;
        case 2 : do_things_with_list<int>() ; break ;
        case 3 : do_things_with_list<double>() ;
        default: std::cerr << "invalid choice\n" ;
    }
}
Topic archived. No new replies allowed.