技術の基礎
キーワードtypename
#include "pch.h"
#include <iostream>
#include<string>
using namespace std;
class U
{
public:
U():i(100)
{
cout << "U()" << endl;
}
public:
static int sub;
typedef unsigned int UINT4;
UINT4 i;
};
int U::sub = 100;
template<typename T>
class A
{
private:
int p;
public:
A():p(10)
{
cout << "A()" << endl;
}
public:
void func1()
{
U u;
typename U::UINT4 *q = NULL;
q = &u.i;
*q = 22;
cout << u.i << endl;
}
void func2()
{
int ret = 0;
ret = U::sub * p;
cout << ret << endl;
}
};
int main()
{
A<int> obj;
obj.func1();
obj.func2();
return 0;
}
これを使って
メンバーテンプレート
template<typename T>
class B
{
public:
T a;
public:
B():a(10)
{
cout << "B()" << endl;
}
public:
template<typename K>
void sum();
};
template<typename T>
template<typename K>
void B<T>::sum()
{
K j = K();
cout << a + j << endl;
}
B<int> obj1;
B<float> obj2;
obj2.sum<float>();
テンプレートパラメータ
初期化ゼロ
関数テンプレートの引数として文字列を使用する