与えられた定数値に応じた型のオブジェクトを返すテンプレート

公開:2005-05-13 22:52
更新:2020-02-15 04:36
カテゴリ:c++
/***
与えられた定数値に応じた型のオブジェクトを返すテンプレート
***/
#include "iostream"
#include "boost/mpl/list.hpp"
#include "boost/mpl/list_c.hpp"
#include "boost/mpl/at.hpp"
#include "boost/mpl/index_of.hpp"
using namespace boost::mpl;
struct c {
void f ()
{
std::cout << "c::f()" << std::endl;
}
};
struct d {
void f ()
{
std::cout << "d::f()" << std::endl;
}
};
struct e {
void f ()
{
std::cout << "e::f()" << std::endl;
}
};
enum b {
c_,
d_,
e_
};
// 定数型リスト
typedef list_c<int,c_,d_,e_> int_list;
//  クラス型リスト
typedef list <c,d,e> class_list;
struct a
{
// 与えられた定数に応じたクラス型を返却する
template <int c> struct data_func_type
{
typedef typename at
<
class_list,
typename index_of
<
int_list,
typename integral_c
<
int,c
>::type
>::type
>::type    type;
};
template<int p>  typename data_func_type<p>::type data()
{
return data_func_type<p>::type();
};
};
int main()
{
a a_;
// cを返す
a_.data<c_>().f();
// dを返す
a_.data<d_>().f();
// eを返す
a_.data<e_>().f();
return 0;
}
実行結果
c::f()
d::f()
e::f()