編集:サンプルを編集して、私が抱えている問題によりよく似るようにしました。関数は(テンプレート パラメーターだけでなく)通常のパラメーターに依存するようになりました。これは、コンパイル時に計算を行うことができないことを意味します。
手書きのタイプリストでいくつかのコードを書きましたが、今はブーストmpl
を使い始めており、それをライブラリに移動しようとしています。
のまともなドキュメントが見つからないようでmpl::list
、コードを に移植することさえできていませんboost::mpl
。コードの移植に成功したとしても (仮に?)、それは慣用的なものにはならないと感じています。次のコードの書き方を教えてくださいboost
(これは実際のコードではなく、わざと単純化したものであることに注意してください)。
元のコード (codepad.org 貼り付け)
class nil {};
template <class Head, class Tail = nil>
struct type_list {
typedef Head head;
typedef Tail tail;
};
template <class List>
struct foo;
template <class Head, class Tail>
struct foo<type_list<Head, Tail> >{
template <class T>
static void* bar(T* obj, size_t size)
{
if (sizeof(Head) == size)
return reinterpret_cast<Head*>(obj);
// Otherwise check the rest of the list
return foo<Tail>::bar(obj, size);
}
};
template <>
struct foo<nil>
{
template <class T>
static void* bar(T*, size_t) { return NULL; }
};
#include <iostream>
int main()
{
int n = 3;
void *p = foo<type_list<char, type_list<bool,
type_list<double, type_list<long> > > >
>::bar(&n, 4);
std::cout<< p << std::endl;
}
Boost の使用に失敗しました (codepad.org の貼り付け)
#include <boost/mpl/list.hpp>
template <class List>
struct foo{
template <class T>
static void* bar(T* obj, size_t size)
{
typedef typename boost::mpl::front<List>::type type;
if (sizeof(type) == size)
return reinterpret_cast<type*>(obj);
// Otherwise check the rest of the list
return foo<typename List::next>::bar(obj, size);
}
};
template <>
struct foo<boost::mpl::list0<boost::mpl::na> >
{
template <class T>
static void* bar(T*)
{
return NULL;
}
};
#include <iostream>
int main()
{
int n = 3;
void *p = foo<boost::mpl::list<char, bool, double, long> >::bar(&n, 4);
std::cout << p << std::endl;
}