c++ - 我应该使用 switch 语句从变量创建 C++ 模板化对象吗?

标签 c++ templates switch-statement

我需要创建模板类的多个对象。在最终的应用程序中,模板参数将是一个整型变量。由于变量不能用作模板参数,因此我创建了一个 switch 语句来创建对象。

这样做的问题是实例化的对象在 switch 语句的范围之外不可用。在下面的示例中,我通过多次包含 section.tell() 来解决这个问题。我宁愿有一个语句,而不是每个 case 语句都有一个语句,正如我所展示的那样。

问题:

  1. 如何在 switch 语句范围之外使用变量?
  2. 这是解决此问题的最佳方法吗?
#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 .

你能做的是

  1. 定义一个接口(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; 
              } 
     };
    
  2. 绑定(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/

相关文章:

c++ - 使用 opengl 2 从鼠标转换光线

javascript - mooml 模板在尝试渲染时返回 null

c++ - 避免枚举作为接口(interface)标识符 C++ OOP

c++ - 具有多个模板参数的模板容器与具有不同模板参数的其他模板容器交互

c - while 循环内的 switch 语句。我如何重复用户的选择?

java - 在 switch 语句中重用代码 (Java)

C++ Local var in dynamic, on stack?

c++ - VS2017 MFC 断言 : f:\dd\vctools\vc7libs\ship\atlmfc\include\afxwin2. inl 行:84

c++ - 为什么 1.0 乘以 5 得到输出 5 而不是 5.0?

javascript - 使用 Javascript 在 case 语句中打开正则表达式比较的结果