用于生成 pybind11 绑定的模板元函数
Template metafunctions to generate pybind11 bindings
我正在尝试使用 pybind11 为某些C++函数创建 python 绑定。这些函数是模板化的,但在 python 绑定中,我需要其中一个模板参数作为函数参数。目前我的方式是每个模板参数的大量重复。
enum MyEnum {E1, E2, E3};
template<typename T, MyEnum E>
returnType templFunction(int arg){
<function body>
}
PYBIND11_MODULE(moduleName, m){
m.def("pyFunction1", [](int arg, MyEnum e){
switch(e){
case MyEnum::E1: return templFunction<templParam1, E1>(arg);
case MyEnum::E2: return templFunction<templParam1, E2>(arg);
case MyEnum::E3: return templFunction<templParam1, E3>(arg);
default: throw std::invalid_argument("Unknown enum type ...");
}
});
m.def("pyFunction2", [](int arg, MyEnum e){
switch(e){
case MyEnum::E1: return templFunction<templParam2, E1>(arg);
case MyEnum::E2: return templFunction<templParam2, E2>(arg);
case MyEnum::E3: return templFunction<templParam2, E3>(arg);
default: throw std::invalid_argument("Unknown enum type ...");
}
});
// for template type temlParam3, only E1 and E2 are valid enums
m.def("pyFunction3", [](int arg, MyEnum e){
switch(e){
case MyEnum::E1: return templFunction<templParam3, E1>(arg);
case MyEnum::E2: return templFunction<templParam3, E2>(arg);
default: throw std::invalid_argument("Unknown enum type ...");
}
});
// more specializations like above
};
有没有一种好方法可以制作一个高阶函数,这样我就不需要那么多重复的代码了?
我还有其他具有类似签名和模板参数的函数。因此,理想情况下,我想将函数句柄(或函数名称)和模板参数之一传递给"元函数",该函数可以根据枚举和给定的模板参数生成专用化。
注意:我在每个模板类型(templParam1
、templateParam2
、...)上都有一个静态属性,它决定了该模板参数允许的枚举类型。例如templParam1::allowedEnumTypes = std::vector<myEnum> { E1, E2, E3 };
你可以写
template<typename T, MyEnum... Cases>
return_type switcher(int arg, MyEnum e)
{
return_type r;
bool tests[] = {(e == Cases ? (r = templFunction<T, Cases>(arg), true) : false)...};
for(auto t : tests)
if(t)
return r;
throw std::invalid_argument("Unknown enum type ...");
}
并用作
m.def("pyFunction1", switcher<templParam1, E1, E2, E3>);
m.def("pyFunction2", switcher<templParam2, E1, E2, E3>);
m.def("pyFunction3", switcher<templParam3, E1, E2>);
相关文章:
- 将自由函数绑定为类成员函数
- 有没有办法将重载的类函数绑定到函数对象?
- 如何将类 1 的 std::函数绑定到类 2 的函数?
- 如何将 STL 队列推送函数绑定到 std::函数?
- 如何在 C# 中将带有参数的函数绑定到包中
- 如何仅使用 c/python API 将 c++ 成员函数绑定到 python?
- 将非静态函数绑定到回调时出现问题
- 意外输出..函数绑定在虚拟表中的发生方式
- 将类实例函数绑定到 v8::FunctionTemplate
- 是否可以将匿名 lambda 函数绑定到对象以允许 lambda 中的代码访问对象的成员?
- 使用JNI将C 类成员函数绑定到Java
- 将静态成员函数绑定为回调
- 如何使用 boost::bind 将静态成员函数绑定到 boost::function
- 如何将C++函数绑定到xaml文本块属性
- boost::使用成员函数绑定回调的帮助
- 如何将成员函数绑定到 C++14 中的对象
- std::函数绑定到成员函数
- 将带有unique_ptr参数的函数绑定到 std::function<void()>
- 将常规函数绑定到 std::function
- std::将成员函数绑定到 nullptr 处的实例,导致看似随机的 this 指针