[Cython] Feature Request: Variadic Templates

Michael Enßlin michael at ensslin.cc
Mon Jun 22 04:04:33 CEST 2015


I'd like to see support for variadic template arguments, such as this:


template<typename RetT, typename ... VARARGS>
RetT foo(VARARGS ...);


cdef extern from "test.h":
    cdef RetT foo[RetT, ... VARARGS](... VARARGS)

def test():
    cdef int i = foo[int, float, int](1, 2.5, 3)

This would allow Cython's libcpp to easily support many of C++11's new
types, including std::tuple and std::function.

Support for the latter in particular would prove quite useful in passing
around function pointers between Cython and C++.

I have tried to implement this feature myself, but I'm entirely
unfamiliar with Cython's codebase, and all my attempts ended in
unsatisfactorily hacky, unstable code.
I believe that any experienced Cython developer on this list would be
able to properly implement this in a matter of a few hours, as it seems
like a rather minor feature.

The current workaround for the non-existance of this feature involves
typedefs for every possible number of arguments, like this:

template<typename ... Ts>
struct S {};

using S0 = S<>;

template<typename T0>
using S1 = S<T0>;

template<typename T0, typename T1>
using S2 = S<T0, T1>;

template<typename T0, typename T1, typename T2>
using S3 = S<T0, T1, T2>;

then exporting all of S0, S1, ... individually in the .pxd file.

This is inconvenient, but acceptable.

Now assume that S has a member function f,

	template<typename ... Us>
	void f(Ts..., Us ...);

due to the nature of C++, the same trick as above does not work, and the
user will be forced to clutter the C++ code with a function body for
every possible len(Us). Even worse, the .pxd file will now contain a
quadratic number of wrappers (one for every possible combination of
len(Ts), len(Us)), all of them extremely prone to mistakes.

Thanks for reading,

  ~ Michael

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/cython-devel/attachments/20150622/9e9a20da/attachment.sig>

More information about the cython-devel mailing list