可以使用伪类型映射来完成。下面是一些使用 boost::mpl 的示例代码。“Implem”的显式定义可以通过每个对应的implem头文件中的宏来完成。
#include <iostream>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/mpl/empty_sequence.hpp>
#include <boost/type_traits/is_same.hpp>
using namespace boost::mpl;
using namespace boost;
// A type map. Implem #N of type Key is type (default: void)
template <typename Key, int N>
struct Implem
{
public:
typedef void type;
};
// Type vector building functions
// void, the default type, is used to stop the recursion
template <typename Key, int N = 1>
struct ImplemToList;
template <typename Key, typename Item, int N>
struct ImplemListItem
{
public:
typedef typename push_front<typename ImplemToList<Key, N + 1>::type, Item>::type type;
};
template <typename Key, int N>
struct ImplemToList
{
public:
typedef typename Implem<Key, N>::type item;
typedef typename eval_if<is_same<item, void>,
identity<vector<> >,
ImplemListItem<Key, item, N> >::type type;
};
// Example code: an interface with two implems
class Interface
{
public:
virtual const char* name() const = 0;
};
class Implem1 : public Interface
{
public:
virtual const char* name() const { return "implem_1"; }
};
class Implem2 : public Interface
{
public:
virtual const char* name() const { return "implem_2"; }
};
template <>
struct Implem<Interface, 1>
{
public:
typedef Implem1 type;
};
template <>
struct Implem<Interface, 2>
{
public:
typedef Implem2 type;
};
void print(Interface const& i)
{
std::cout << i.name() << std::endl;
}
int main()
{
typedef ImplemToList<Interface>::type IList;
for_each<IList>(&print);
}