template で Class を渡す

template で Class を渡すことも出来ます。

前田稔の超初心者のプログラム入門

プログラムの説明

  1. Str1 と Str2 の二種類の Class を定義して template 関数に渡してみましょう。
    Str2 には m_name[] が定義されていない代わりに m_ten3, m_ten4 が定義されています。
    typedef class
    { public:
        char    m_name[24];
        int     m_ten1;
        int     m_ten2;
    }   Str1;
    typedef class
    { public:
        int     m_ten1;
        int     m_ten2;
        int     m_ten3;
        int     m_ten4;
    }   Str2;
    Str1    str1 = { "愛知 真唯子", 80, 90 };
    Str2    str2 = { 53, 64, 75, 86 };
    
  2. m_ten1 と m_ten2 の和を求める template 関数です。
    <class Type> で呼び出し側から渡された型を仮に Type で受け取ります。
    template<class Type>
    int  Sum(Type* str)
    {
        return str->m_ten1+str->m_ten2;
    }
    
  3. 呼び出し側は次のようになります。
        printf("str1 Sum=%d\n",Sum(&str1));
        printf("str2 Sum=%d\n",Sum(&str2));
    

超初心者のプログラム入門(C/C++)