简体   繁体   中英

C++ Template Class Initialization in Condition Statements

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:

  • Reorder the code so that the code at the end of main is implemented in a templated function, call that function with different arguments depending on the code path

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;
  };
}
  • Use dynamic polymorphism. Implement a base type with a virtual interface, instantiate one of the templates (that inherit from the interface type) inside the different branches and set a pointer accordingly.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM