Rob*_*cus 5 c++ python templates boost word-wrap
我正在尝试使用 boost.python 将以下 c++ 函数公开给 python:
template <typename genType>
genType refract(
genType const & I,
genType const & N,
typename genType::value_type const & eta);
Run Code Online (Sandbox Code Playgroud)
我得到的是这个:
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>);
}
Run Code Online (Sandbox Code Playgroud)
编译时出现以下错误:
错误 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>);
}
Run Code Online (Sandbox Code Playgroud)
从参考资料中,floor()定义如下:
template< typename genType >
genType floor (genType const &x)
Run Code Online (Sandbox Code Playgroud)
我可以将其构建为 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>);
}
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
小智 3
这不是完美的答案,因为它需要滥用类型系统并编写大量额外的粘合代码。
您可以尝试定义一个包装模板来装饰您的目标类型,以便它具有必要的 typedef 来满足调用函数(反射)。
这个例子展示了这种方法的失败。请注意,此反射函数执行简单的加法;但是,为了让 C++ 识别模板化类型 N 的运算符+,包装器必须显式定义它。
#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;
}
Run Code Online (Sandbox Code Playgroud)