zoukankan      html  css  js  c++  java
  • variadic template (2)

    在上一部分中,完成了一个简单的使用可变模板函数printf1 的编写以及初步尝试,以下是我对可变模板类的理解以及初步使用记录。

    上一部分中,可变模板函数是通过 不断地调用类似递归的操作来完成对 parameter pack 不断解包(我感觉拆分更贴切一点)实现。

    而可变模板类 则是通过不断的继承自身,并不断实例化此模板参数的类定义,并提升为父类的方法实现。(表达的有点不清楚,可以跳过这一句直接看下面的描述)

    可变模板类定义为:

    template<typename... Elements> class tuple;
    template<typename Head,typename... Tail>
    class tuple<Head,Tail...>:public tuple<Tail ...>{
        Head head;
    public:
        Head get_head(){return head;}
        void set_head(Head he){head=he;}
    };
    template<>
    class tuple<>{
    };

    当我们定义一个 对象 :tuple<int,char,string> tu;

    这一句话实际完成的工作有(假设这是第一次使用这个模板类):

    1. 首先要实例化 tuple<int,Tail ..(char,string)> 因为它需要继承模板参数为tuple<char ,Tail ...(string)>类,
    2. 若tuple<char ,Tail ...(string)>存在则返回1,否则实例化 tuple<char ,Tail ...(string)>类,他继承自  tuple<string,Tail ...(NULL)>类
    3. 若tuple<string,Tail ...(NULL)>存在则返回2,否则实例化  tuple<string,Tail ...(NULL)>,它继承自tuple<>,此类已存在直接创建
    4. #include<iostream>
      #include<string>
      #include<exception>
      #include<stdexcept>
      using namespace std;
      
      template<typename... Elements> class tuple;
      template<typename Head,typename... Tail>
      class tuple<Head,Tail...>:public tuple<Tail ...>{
          Head head;
      public:
          Head get_head(){return head;}
          void set_head(Head he){head=he;}
      };
      template<>
      class tuple<>{
      };
      
      class A
      {
      public:
          int num;
      };
      
      int main()
      {
          tuple<string,int,A> tu;
          tu.set_head("aklsjdf;l");
          tu.tuple<int,A>::set_head(23);
          cout << tu.get_head() << endl;
          cout << tu.tuple<int,A>::get_head() << endl;
          
          A a;
          a.num=2323;
          tu.tuple<A>::set_head(a);
          cout << tu.tuple<A>::get_head().num << endl;
          
          return 0;
      }

       调用方法直接使用作用于操作符即可,跟普通的调用父类同名方法一样。

  • 相关阅读:
    STDMETHOD (转)
    DirectX中的纹理映射相关技术 (转)
    (转)清空std::stringstream,联系到stream的clear()和清空
    (转载)MultiAnimation
    (转)SkyBox
    [转载]漫谈游戏中的阴影技术
    反射矩阵计算
    (转)COM组件里的AddRef()
    LINQ简记(2):重要概念
    继续聊WPF——自定义命令
  • 原文地址:https://www.cnblogs.com/justboy/p/6626369.html
Copyright © 2011-2022 走看看