我需要创建模板类的多个对象。在最终的应用程序中,模板参数将是一个整型变量。由于变量不能用作模板参数,因此我创建了一个 switch
语句来创建对象。
这样做的问题是实例化的对象在 switch
语句的范围之外不可用。在下面的示例中,我通过多次包含 section.tell()
来解决这个问题。我宁愿有一个语句,而不是每个 case
语句都有一个语句,正如我所展示的那样。
问题:
- 如何在
switch
语句范围之外使用变量? - 这是解决此问题的最佳方法吗?
#include <iostream>
template < int MF >
class Section {
public:
void tell(){std::cout << "\tI am MF = " << MF << ".\n";}
};
int main(int argc, char* argv[])
{
std::cout << "\nCreating Sections based on an iterative." << std::endl;
for( int i=0; i<5; i++){
std::cout << "i = " << i;
switch(i){
case 1:{
Section<1> section;
// Make Section tell us who it is
section.tell();
break;
}
case 2:{
Section<2> section;
// Make Section tell us who it is
section.tell();
break;
}
default:
std::cout << "\tI don't know how to do this." << std::endl;
}
// section.tell(); // Wish I could do this
}
return 0;
}
最佳答案
你正在做的事情在某种程度上接近 class factory pattern .
你能做的是
定义一个接口(interface)(抽象类)
ISection
它作为您的Section<T>
的基类模板类。class ISection{ public: virtual void tell() = 0; virtual ~ISection(){}; }; template <int i> class Section : public ISection { public: /* tell() is overridden and (in this setting) it is parametrized by i */ void tell(){ /*some thing, e.g.*/ std::cout << "i = " << i << std::endl; } };
绑定(bind)您的
Section<T>
实例(无论其中哪个,取决于模板参数)通过ISection
(智能)指针,例如std::shared_ptr<ISection> myInstance( new Section<1>() ) ;
因此,在 switch
框架,你会有类似的东西
std::shared_ptr<ISection> myInstance;
switch (i):
case 1:
myInstance = std::shared_ptr<ISection>(new Section<1>());
break;
case 2:
myInstance = std::shared_ptr<ISection>(new Section<2>());
break;
等等。
最后,您可以调用方法 tell()
通过
myInstance->tell();
.
关于你的第二个问题,我想说,除非你的模板参数是实际类型(即不是静态 int
值),否则我不会使用这样的模板机制。
相反,我会简单地传递 int
非模板类的构造函数的参数,即
Section mySection(i);
。
当然,另一方面,您可能想在 i
上玩一些黑暗的元编程技巧。 .
关于c++ - 我应该使用 switch 语句从变量创建 C++ 模板化对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100549/