我正在尝试使用 boost.python 将以下 c++ 函数公开给 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 个参数 - 提供 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.
最佳答案
这不是完美的答案,因为它需要滥用类型系统并编写大量额外的粘合代码。
您可以尝试定义一个包装器模板来装饰您的目标类型,使其具有必要的类型定义来满足调用函数(反射)。
这个例子展示了这种方法的失败。请注意,这个反射函数执行了一个简单的加法;然而,为了让 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;
}
关于c++ - 用 boost.python 包装一个模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6537553/