我想有一个类模板能够存储一个函数对象接受正是“N”双参数。这个伪代码使用了一个不存在的std::repeated_type
函数模板来解决这个问题,并说明了预期的用法:
template<int N>
class FunctionHolder {
public:
using function_type = std::function<int(std::repeated_type<double, N> args)>;
FunctionHolder(const function_type& arg): m_func(arg) {}
private:
const function_type& m_func;
};
int my_func(double arg1, double arg2);
void main() {
FunctionHolder<2> my_holder(my_func);
}
字符串
我希望代码最大程度地简单和可读,所以即使我模糊地理解我可以使用std::integer_sequence和helper类模板来缝合解决方案,但我不相信我的解决方案足够简单。
6条答案
按热度按时间jfewjypa1#
您可以递归地将函数参数添加到模板列表中:
字符串
这可以被访问为
RepeatFunctionArgType<int,3,double>::type
。型
b4wnujal2#
你可以在未求值的上下文中使用lambda来获取其返回类型:
字符串
交替地
型
A more generic solution adapted from 康桓瑋's code in the comments could look like this:
型
旁注:
const function_type&
成员不是一个好主意,除非您实际提供的std::function<...>
比FunctionHolder
寿命长。您的示例创建了一个临时std::function<...>
,该临时std::function<...>
将在FunctionHolder
的构造完成后立即过期。我建议将其设为常规非参考成员:
型
kxkpmulp3#
使用helper class template,它可能是
字符串
x0fgdtte4#
下面是一个C++17的解决方案,你不需要在main()中显式地专门化保持器,也不需要显式地声明参数的数量。
字符串
5cnsuln75#
像这样的东西怎么样:
字符串
https://godbolt.org/z/cjEq4s7Ef
当然,它使用工厂函数,但也可以使用演绎指南来实现。一切都是为了测试而公开的,根据你的喜好调整它。
mepcadol6#
可以使用
std::array<double, N>
作为函数的参数(而不是单独的
double
参数):字符串
Demo - Godbolt的