我有以下场景:
class C
{
public:
template <typename T>
std::shared_ptr<T> foo();
std::shared_ptr<SomeClass> foo(std::string_view sw);
};
class DerivedFromC : public C
{
// no logic concerning foo
};
// in my bindings
pybind11::class_<DerivedFromC, ...some options...>(m, "Name")
.def("foo", pybind11::overload_cast<std::string_view>(&DerivedFromC::foo));
此代码编译时不会出现错误消息:
[build] pythonbind.hpp(51,21): error: no matching function for call to object of type 'const detail::overload_cast_impl<basic_string_view<char, char_traits<char>>>'
[build] 51 | .def("foo", pybind11::overload_cast<std::string_view>(&DerivedFromC::foo));
[build] | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[build] ...\build\vcpkg_installed\x64-windows\include\pybind11/detail/common.h(1106,20): note: candidate template ignored: couldn't infer template argument 'Return'
[build] 1106 | constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
[build] | ^
[build] ...\build\vcpkg_installed\x64-windows\include\pybind11/detail/common.h(1111,20): note: candidate template ignored: couldn't infer template argument 'Return'
[build] 1111 | constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
[build] | ^
[build] ...\build\vcpkg_installed\x64-windows\include\pybind11/detail/common.h(1117,20): note: candidate function template not viable: requires 2 arguments, but 1 was provided
[build] 1117 | constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
[build] | ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我做错了什么或者有特殊的方法来检索该函数的指针吗?对我来说,感觉
overload_cast
函数应该选择正确的重载,因为模板化函数没有任何参数。
我通过手动
static_cast
-ing 到正确的签名解决了我的问题,如下所示。
pybind11::class_<DerivedFromC, ...some options...>(m, "Name")
.def("foo", static_cast<std::shared_ptr<SomeClass>(DerivedFromC::*)(std::string_view)>(&DerivedFromC::foo));
但是,这对我来说似乎并不优雅。因此,如果有人有更好(更优雅)的解决方案,就会将此作为答案。