2

I have this kind of code :

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;
}

Is there a way to make a loop over templates types T2 to T5 to avoid redundant code ?

Note: I don't use C++11. I use boost.

Caduchon
  • 4,574
  • 4
  • 26
  • 67

2 Answers2

1

If you are already using boost, you should use boost::mpl::* containers as your type lists. Than you can parametrize your template with such a list and use reach mpl capabilities for handling type lists.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
1

Yes you can with the Boost MPL using the facilities of boost::mpl::vector and boost::mpl::for_each like the example below:

Live Demo

Code:

#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;    
 }
}
101010
  • 41,839
  • 11
  • 94
  • 168