是否可以遍历模板参数?

Is it possible to loop over template parameters?

我有这样的代码:

template <typename T1,
          typename T2 = void,
          typename T3 = void,
          typename T4 = void,
          typename T5 = void>
std::set<std::type_info const*> MyClass<T1,T2,T3,T4,T5>::get_types()
{
    std::set<std::type_info const*> t;
    t.push_back(&typeid(T1));
    if(typeid(T2) != typeid(void))
      t.push_back(&typeid(T2));
    else
      return;
    if(typeid(T3) != typeid(void))
      t.push_back(&typeid(T3));
    else
      return;
    if(typeid(T4) != typeid(void))
      t.push_back(&typeid(T4));
    else
      return;
    if(typeid(T5) != typeid(void))
      t.push_back(&typeid(T5));
    else
      return;
}

有没有办法循环模板类型 T2T5 以避免冗余代码?

注意:我不使用 C++11。我用boost.

如果您已经在使用 boost,则应使用 boost::mpl::* 容器作为类型列表。然后您可以使用这样的列表参数化您的模板,并使用 reach mpl 功能来处理类型列表。

是的,您可以使用 Boost MPL using the facilities of boost::mpl::vector and boost::mpl::for_each,如下例所示:

Live Demo

代码:

#include <iostream>
#include <typeinfo>
#include <vector>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/placeholders.hpp>

template <typename T>
struct wrap {};

class Bar {
  std::vector<std::type_info const*> &types;
public:
  Bar(std::vector<std::type_info const*> &types_) : types(types_) {}
  template<typename T> void operator()(wrap<T>) const { 
    if(typeid(T) != typeid(void)) types.push_back(&typeid(T));
  }
};

template<typename T1, typename T2 = void, typename T3 = void, typename T4 = void, typename T5 = void>
struct Foo {
  std::vector<std::type_info const*> get_types() const {
    std::vector<std::type_info const*> out;
    boost::mpl::for_each<boost::mpl::vector<T1, T2, T3, T4, T5>, wrap<boost::mpl::placeholders::_1> >(Bar(out));
    return out;
  }
};

int main() {
 Foo<int, long, double> foo;
 std::vector<std::type_info const*> types = foo.get_types();

 for(int i(0), isz(types.size()); i < isz; ++i) {
   std::cout << types[i]->name() << std::endl;    
 }
}