[英]C++ Template Class Initialization in Condition Statements
我試圖讓用戶選擇模板是int,double還是字符串。 但是使用我的方法存在繼承問題,因為我使用If語句來初始化類模板對象,每當我想進行方法調用時,編譯器都會拋出錯誤。
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;
}
因為我這樣做,所以當我嘗試調用setBar()
時,我得到一個錯誤,說“v1在這個范圍內沒有被刪除”。 如何通過此操作並允許用戶選擇AND允許方法調用? 我知道如果我沒有使用模板,我可以在if語句之前聲明它,但是對於編譯器要求的模板,我告訴它我想要的類型。 謝謝!
在嘗試時無法完成此操作。 第一個問題是不同的變量v1
是在不包括后來使用的范圍中定義的。 可以采取不同的解決方法,其中首先想到的是:
例
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;
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.