I'm trying to allow the user to choose if the template is a int, double, or string. But with my method there is an inherit problem, since I'm using If-statements to initialize the class template object, the compiler will throw an error whenever I want to make a method call.
template<class T>
class foo {
private:
int bar
public:
void setBar(int newBar);
};
template<class T>
void foo<T>::setBar(int newBar) {
bar = newBar;
}
int main() {
int inputType;
cout << endl << "1 for integer, 2 for double, 3 for strings." << endl <<
"What kind of data do you wish to enter?(1-3): ";
cin >> inputType;
if(inputType == 1) {
foo<int> v1;
} else if(inputType == 2) {
foo<double> v1;
} else if(inputType == 3) {
foo<string> v1;
} else {
cout << "Error - Please enter in a proper #: ";
}
//Compiler Error
v1.setBar(3);
return 0;
}
Since I'm doing it this way, I get an error saying "v1 was not delcared in this scope" whenever i try to call setBar()
. How do I get past this and allow the user to choose AND allow for method calls? I know if I weren't using templates I could just declare it before the if-statements, but with templates the compiler demands I tell it what type I want first. Thanks!
This cannot be done as you are attempting it. The first problem being that the different variables v1
are defined in scopes that don't include the later use. There are different workarounds that can be taken, of which the first two that come to mind are:
Example
template <typename T>
void process() {
foo<T> v1;
v1.setBar(3);
}
int main() {
// …
switch (input) {
case 1: process<int>(); break;
case 2: process<double>(); break;
default: process<string>(); break;
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.