问题
我正在尝试编写一个函数,它可以在参数包中搜索特定类型,然后创建一个lambda表达式,使用该类型作为模板参数调用另一个函数,例如:
auto fn = findType<MyType, SomeType, OtherType>("OtherType");
fn(otherFn) == otherFn<OtherType>();
我想写出像这样的文章:
template<class T, class ...Ts>
auto findType(const std::string& name) {
if (refl::is_reflectable<T>() && refl::reflect<T>().name == name) {
return []<class Fn>(Fn fn) {
fn<T>();
};
}
return findType<Ts...>(name);
}
然而,C++似乎无法识别
fn
可以带有模板类型的参数。我使用的是gcc10和C++20,所以如果可能的话,我也可以使用概念。
我相信问题可以总结为:如何将一个模板参数化的函数传递到另一个函数中?
template<class C>
void fn() {}
template<class Fn, class Arg>
void mainFn(Fn fn) {
fn<Arg>(); // ???
}
尝试的搜索
我曾经查看过模板模板参数,但那似乎只适用于对类型进行模板化,而不是函数调用。
我也看过 C++ 概念,但 std::invokable
不接受模板参数,要求也似乎不允许这样的表达式:
return []<class Fn>(Fn fn) requires requires { fn<T>(); } {
auto fn = []<class C>(C c) {};
。类似auto fn = []<class C>() {};
的写法似乎不起作用,这也是我在这个问题中遇到的情况。 - Moon CheesezfindType
中返回lambda表达式不是一个好选择。函数模板的不同实例中的lambda表达式类型不同,这使得findType
的返回类型不匹配。 - RedFog