type declaration real time?

Hello. I am trying to make a simple program that asks for user input. then outputs it. But you don't know what type of value the user is going to input.
I thought this was what templates were for? I created a class like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 template <class T>
class input{
private:
T value;

public:
    T makeinput(){

     std::cin >> value;
     return value;
     }
    void display(){
    std::cout << value;
    }
};

(im really new to templates) Then i did this in main and realised it still has to be declared before runtime
1
2
3
4
5
6
7
8
9
int main()
{
input < >one;// <--- still has to be declared?
one.makeinput();
one.display();

return 0;
}

how would you make it define that in realtime? like if the input is a string, its stored as a string. or is this not possible?
like if the input is a string, its stored as a string. or is this not possible?
It is not possible. All (possible) types should be known in compile time. Even without that, compiler cannot read your mind.
Think logically: is input 123 is integer 123, double 123.0 or string "123"?

You can get your input as string, determine input type and create instance of needed type.
Last edited on
oh i didnt think of that.. Yeah that makes sense.
You can make use of the templates when an operation is similar for different data types like adding, subtracting, multiplying and dividing two numbers as follows:

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
#include <iostream>
#include <string>

using namespace std;

template<class MT>
MT calculate_sum(MT num_a, MT num_b)
{
    return num_a+num_b;    
}

int main()
{
    int a = 5, b = 3;
    
    cout << calculate_sum(a, b);
    cout << endl;
    
    float c = 5.5, d = 5.0;
    
    cout << calculate_sum(c, d);
    cout << endl;
    
    return 0;
}


Use generic functions (templates) if Implementation of a function is same but the type of arguments may differ. In this way you don't need to overload functions with same number of parameters and implementation.
Last edited on
Topic archived. No new replies allowed.