Pybind11 cannot bind the Template? #3534
-
I wrote the function implementation, definition and pybind binding in three files respectively. The first case can work normally(Below is the corresponding code). #include "ops.h"
int add(int a, int b) {
return a + b;
} #ifndef OPS_OPS_H
#define OPS_OPS_H
int add(int a, int b);
#endif //OPS_OPS_H #include "pybind11/pybind11.h"
#include "ops.h"
PYBIND11_MODULE(ops, m) {
m.def("add", &add);
} There will be errors in the template(The following is the corresponding code and error message). #include "ops.h"
template<typename T>T add(T a, T b) {
return a + b;
} #ifndef OPS_OPS_H
#define OPS_OPS_H
template<typename T>T add(T a, T b);
#endif //OPS_OPS_H #include "pybind11/pybind11.h"
#include "ops.h"
PYBIND11_MODULE(ops, m) {
m.def("add", &add<int>);
m.def("add", &add<float>);
} ImportError: dlopen(ops.cpython-38-darwin.so, 0x0002): symbol not found in flat namespace '__Z3addIfET_S0_S0_' I want to ask if this is a bug. If not, how can I divide the template function into three files(Function implementation, function definition and pybind binding)? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You havn't instantiated your template functions. To explain further the template function in your .cpp file doesn't get compiled until it is 'used' in the same 'compilation unit'. Best bet to understand this is to use google to learn about this or see this link: https://riptutorial.com/cplusplus/example/28734/explicit-instantiation |
Beta Was this translation helpful? Give feedback.
You havn't instantiated your template functions.
To explain further the template function in your .cpp file doesn't get compiled until it is 'used' in the same 'compilation unit'.
You can solve this by either putting your template code into the header which is normally what you'd do. Or if you really need the code in the cpp for whatever reason you need to 'explicitly instantiate' the functions for the requirted type.
Best bet to understand this is to use google to learn about this or see this link: https://riptutorial.com/cplusplus/example/28734/explicit-instantiation