I would like to have a class template capable of storing a functional object accepting exactly "N" double arguments. This pseudo-code uses a non-existing std::repeated_type
function template that would solve the problem and illustrates the intended usage:
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);
}
I want the code to be maximally simple and readable, so even though I vaguely understand I can stitch a solution using a std::integer_sequence and helper class templates, but I don't feel confident that my solution would be simple enough.
You can recursively add function arguments to a template list:
template <typename Ret, std::size_t N, typename Type, typename... T>
struct RepeatFunctionArgType {
static auto fnt() {
if constexpr (sizeof...(T) >= N) {
return std::function<Ret(T...)>{};
} else {
return RepeatFunctionArgType<Ret, N, Type, Type, T...>::fnt();
}
}
using type = decltype(fnt());
};
This can be accessed as RepeatFunctionArgType<int,3,double>::type
.
static int foo(double,double,double) {return 0;}
int main() {
RepeatFunctionArgType<int,3,double>::type fn = foo;
}