Search code examples
pythonc++parameter-pack

Iterate over parameter pack of types


I'm trying to simplify usage of pybind11 when binding templates. For now I have a parameter pack of types and I need to call a function cl.def() (look at the code below) with each type from that parameter pack. Also there is a vector of names and each name corresponds to parameter's pack type. Here is an example:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
 
namespace py {
 
template <typename T>
class class_ {
public:
    template <typename R, typename ...Args>
    class_ & def(char const *, R (T::*)(Args...)) {
        return *this;
    }
};
 
} // py
 
template <typename ...>
struct tl{};
 
template <typename T>
struct type_identity {
    using type = T;
};
 
template <typename T>
static T deduce(type_identity<T>);
 
template <
    typename Apply
  , typename T
  , typename ...Inst
    >
void class_group_def(
    Apply &&func, 
    py::class_<T> & cl, 
    char const * func_name_py, 
    tl<Inst...>)
{
    std::string func_name_py_str(func_name_py);
    remove(func_name_py_str.begin(), func_name_py_str.end(), ' ');    // remove spaces
 
    std::stringstream ss(func_name_py_str);
    std::vector<std::string> func_name_py_str_vec;
    std::string token;
    while (std::getline(ss, token, ';')) {
        func_name_py_str_vec.push_back(token);
    }
 
    for (size_t i = 0; i < sizeof...(Inst); i++){
        // I need to call `cl.def` with every `Inst` corresponding to `func_name_py_str_vec[i]`
        (cl.def(func_name_py_str_vec[i].c_str(), func(type_identity<T>{}, type_identity<Inst>{})),...);
    }
}
 
class A {
public:
    template <typename T>
    void write() { }
};
 
#define CLASS_GROUP_DEF(class_name, func_name_c, func_name_py, ...) \
    class_group_def( \
      [](auto f1, auto f2) { \
         return &decltype(deduce(f1))::template func_name_c<decltype(deduce(f2))>; \
      } \
     , class_name \
     , #func_name_py \
     , tl<__VA_ARGS__>{} \
     )
 
 
int main() {
    py::class_<A> myClass;
 
    // names are divided by semicolon ;
    CLASS_GROUP_DEF(myClass, write, writeInt;writeChar, int, float);
}

In for loop I think I need to iterate over types. As I call this function with only two types now (int and float) loop may be unwrapped to something like (this snippet of code aims to describe what I'm trying to achieve):

cl.def(func_name_py_str_vec[0].c_str(), func(type_identity<T>{}, type_identity<Inst[0]>{}));
cl.def(func_name_py_str_vec[1].c_str(), func(type_identity<T>{}, type_identity<Inst[1]>{}));

Is there a way to solve my task (i.e. pass elements from parameter pack alongside other variable corresponding to each of them)?


Solution

  • Don't use a macro for this. Visiting a list of types is fairly straightforward with basic-ish partial specialization:

    #include <iostream>
    
    // This will only ever be used for Visitor<> because of the next specialization.
    // So it serves as the "recursion" stop condition.
    template<typename... Ts>
    struct Visitor {
        template<typename T>
        static void visit(T& v) {}
    };
    
    // This will match any type list with at least one type.
    template<typename First, typename... Rest>
    struct Visitor<First, Rest...> {
      template<typename T>
      static void visit(T& v) {
        // make use of First as the "current" type.
        v.template visit<First>();
    
        // "recurse" for the rest of the types
        Visitor<Rest...>::visit(v);
      }
    };
    
    struct Handler {
        template<typename T> 
        void visit() {
            std::cout << typeid(T).name() << "\n";
        }
    };
    
    int main() {
        Handler handler; 
        Visitor<int, float, char>::visit(handler);
    }
    

    There's probably also a terse way to do it using a fold expression. But this is simple enough, and is compatible with older (C++11) versions of the standard as well.