gpt4 book ai didi

条件语句中的 C++ 模板类初始化

转载 作者:行者123 更新时间:2023-11-28 03:05:04 24 4
gpt4 key购买 nike

我试图让用户选择模板是整数、 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 未在此范围内被删除”。我如何解决这个问题并允许用户选择并允许方法调用?我知道如果我不使用模板,我可以在 if 语句之前声明它,但是对于模板,编译器要求我首先告诉它我想要什么类型。谢谢!

最佳答案

这无法在您尝试时完成。第一个问题是不同的变量 v1 定义在不包括以后使用的范围内。可以采取不同的解决方法,其中首先想到的是:

  • 重新排序代码,使 main 末尾的代码在模板函数中实现,根据代码路径使用不同的参数调用该函数

例子

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;
};
}
  • 使用动态多态性。使用虚拟接口(interface)实现基类型,在不同分支内实例化模板之一(从接口(interface)类型继承)并相应地设置指针。

关于条件语句中的 C++ 模板类初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19920739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com