what’s the right way to export template function from c++ into python using boost.python? Here is the code:
template<typename T>
T getValue(const std::string &key, const T &defaultValue = T()) {}
// Export into some python class:
class_<ConfigManager>(...)
.def("GetValue", getValue<int>)
.def("GetValue", getValue<float>)
.def("GetValue", getValue<std::string>);
And usage:
print GetValue("width")
Boost.Python.ArgumentError: Python argument types in
GetValue(ConfigManager, str)
did not match C++ signature:
GetValue(ConfigManager {lvalue}, std::string, int)
What’s wrong?
You should read the relevant Boost documentation regarding default arguments. I’ll summarize below.
The problem here is that default arguments are used when calling functions in C++. Get rid of them and you’ll see the problem from Python’s perspective:
The fundamental issue is that function types don’t carry default argument information. So how can we simulate it? Essentially, by overloading:
A maintenance hassle. Luckily, Boost makes this easy:
The macro also exists for class members. This is in the documentation, if any of it is unclear.