Skip to content

Template functions #199

@nils-werner

Description

@nils-werner

Is it possible to define template functions like

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

namespace py = pybind11;

template <typename T>
T square(T x) {
    return x * x;
}

void pyexport(py::module& m) {
    m.def("square", &square);
}

I always get error messages like

/var/folders/h9/w6465dvd31l5f4bd_j49_4cw0000gp/T/tmpNUt8Ir/ctest.cpp:50:7: error: no matching member function for call to 'def'
    m.def("square", &square);
    ~~^~~
/virtualenv/include/site/python2.7/pybind11/pybind11.h:487:13: note: candidate template ignored: couldn't infer template argument 'Func'
    module &def(const char *name_, Func &&f, const Extra& ... extra) {
            ^
1 error generated.
error: command 'clang' failed with exit status 1

or, when using py::vectorize

/var/folders/h9/w6465dvd31l5f4bd_j49_4cw0000gp/T/tmpc0aYol/ctest.cpp:49:21: error: no matching function for call to 'vectorize'
    m.def("square", py::vectorize(&square));
                    ^~~~~~~~~~~~~
/virtualenv/include/site/python2.7/pybind11/numpy.h:379:66: note: candidate template ignored: couldn't infer template argument 'Return'
detail::vectorize_helper<Return (*) (Args ...), Return, Args...> vectorize(Return (*f) (Args ...)) {
                                                                 ^
/virtualenv/include/site/python2.7/pybind11/numpy.h:383:31: note: candidate template ignored: couldn't infer template argument 'func'
template <typename func> auto vectorize(func &&f) -> decltype(
                              ^
/virtualenv/include/site/python2.7/pybind11/numpy.h:374:49: note: candidate function template not viable: requires 2 arguments, but 1 was provided
detail::vectorize_helper<Func, Return, Args...> vectorize(const Func &f, Return (*) (Args ...)) {
                                                ^
1 error generated.
error: command 'clang' failed with exit status 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions