-
Templates in c++...
hey all,
i just learned templates in C++ and wanna know how to put them to practical use...
the following example will illustrate my doubt:
Code:
#include<iostream>
using namespace std;
template <class aType>
class com{
public:
com(aType x){
cout << x + 5;
}
};
int main(){
int a = NULL;
double b = NULL;
cout << "enter a number: ";
/* here wha' i wanna do is,
if the user enters a number,
i wanna store it in a... USING A CIN STATEMENT WHICH I HAVEN'T MENTIONED
if the user enters a number with a fraction store it in b... USING A CIN STATEMENT WHICH I HAVEN'T MENTIONED
HOW TO DO THAT IS MY QUESTION...
*/
// if i could do that then i could practically use templates in real programs
//like:
if(a == NULL && b != NULL){
com <double> x(b);
}else if(a != NULL && b == NULL){
com <int> x(a);
}else{
cout << "Sorry there was an error...";
}
}
-
You should read into a string then parse the string (after or during which you determine if the contents can be interpreted as an integer or fraction).
-
I think you may be misunderstanding what templates can do.
Do you understand when a variable goes out of scope, and what that means?
-
Templates are useful when you know the types of something at compile time.
Here, you are deciding the type at runtime (you are deciding something on what the user inputs, which is after the program has been compiled). That's a different beast and requires radically different techniques to achieve.
I'm just giving you a heads up here. Templates are compile-time beasts.