[英]Wrapping a template function with boost.python
我正在尝试使用 boost.Z23EEEB4347BDD26BFCDDZ6B7EE9A3B755 将以下 c++ function 公开给 python
template <typename genType>
genType refract(
genType const & I,
genType const & N,
typename genType::value_type const & eta);
我得到的是:
template<typename N>
N reflect(N const & i, N const & n, typename N::value_type const & eta)
{
return glm::N refract(i,n,eta);
}
BOOST_PYTHON_MODULE(foo)
{
def("reflect", reflect<float>);
def("reflect", reflect<double>);
}
编译时出现以下错误:
错误 C2780: 'void boost::python::def(const char *,F,const A1 &,const A2 &,const A3 &)': 预期 5 arguments - 提供 2
我应该如何包装它?
- - -编辑 - - -
这有效:
template<class T>
T floor(T x)
{
return glm::core::function::common::floor(x);
}
BOOST_PYTHON_MODULE(busta)
{
def("floor", floor<double>);
def("floor", floor<float>);
}
从参考资料中, floor()
定义如下:
template< typename genType >
genType floor (genType const &x)
我可以将其构建为 DLL,然后将其导入 python 并从那里使用 floor()。 生活感觉如此美好……但是……
这行不通,我想了解原因:
template<class genType >
genType reflect (genType i, genType n, genType eta)
{
return glm::core::function::geometric::refract(i, n,eta);
}
BOOST_PYTHON_MODULE(busta)
{
def("reflect", reflect<float>);
}
refract() 定义在这篇文章的顶部。
我现在得到的错误是:
1>foo.cpp(37): error C2893: Failed to specialize function template 'genType glm::core::function::geometric::refract(const genType &,const genType &,const genType::value_type &)'
1> With the following template arguments:
1> 'float'
1> foo.cpp(60) : see reference to function template instantiation 'genType
`anonymous-namespace'::reflect<float>(genType,genType,genType)' being compiled
1> with
1> [
1> genType=float
1> ]
1>
1>Build FAILED.
这不是完美的答案,因为它需要滥用类型系统并编写大量额外的胶水代码。
您可以尝试定义一个包装模板来装饰您的目标类型,使其具有满足调用 function (反射)的必要类型定义。
这个例子展示了这种方法的失败。 注意这个反射 function 执行一个简单的加法; 然而,为了让 C++ 识别模板类型 N 的 operator+,包装器必须明确定义它。
#include <iostream>
using namespace std;
template<class N>
N reflect(const N& n, const typename N::value_type& t)
{
return n + t;
}
template<class N>
struct wrapper
{
typedef N value_type;
wrapper(const N& n):_n(n){}
operator N& () { return _n; }
N operator+ (const N& r) const { return _n + r; }
N _n;
};
int main(int,char**)
{
cout << reflect( wrapper<double>(1), 2.0) << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.