我想要一个代表整数的离散函数的类。函数的功能是模板参数。构造函数应接受此指针的功能(指向吗?)。我还希望能够将lambda表达式传递给构造函数。实际上,这是我将要传递的函数的主要类型。
此外,我想要一种方法eval()
来为提供的参数计算函数的值。
问题是如何传递和存储函数以及如何对其进行评估。
template<int arity>
class DiscreteFun {
private:
FuncType f; // what should FuncType be?
public:
DiscreteFun(FuncType f): f(f) { };
int eval(const array<int,arity>& x) const {
// how to pass arguments so that it calculates f(x[0], x[1], ...)
}
};
最佳答案
您可以使用std::index_sequence
和一些间接方式:
template <std::size_t, typename T>
using always_t = T;
template <typename Seq> class DiscreteFunImpl;
template <std::size_t ... Is>
class DiscreteFunImpl<std::index_sequence<Is...>>
{
private:
std::function<int (always_t<Is, int>...)> f;
public:
DiscreteFunImpl(std::function<int (always_t<Is, int>...)> f): f(f) {}
int eval(const array<int, sizeof...(Is)>& x) const {
return f(x[Is]...);
}
};
template <std::size_t N>
using DiscreteFun = DiscreteFunImpl<std::make_index_sequence<N>>;
关于c++ - 使用模板化Arity存储类函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56580149/