我希望有一个类来表示整数上的离散函数。函数的实参是一个模板参数。构造函数应该接受(指向?)的函数。我还希望能够将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], ...)
}
};发布于 2019-06-13 20:46:22
您可以使用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>>;发布于 2019-06-13 20:50:29
您可以为f类型添加一个模板参数,然后eval就是std::apply。请注意,std::array是一个类似元组的容器。
template<int arity, typename FuncType>
class DiscreteFun {
private:
FuncType f;
public:
DiscreteFun(FuncType f): f(f) { };
int eval(const array<int,arity>& x) const {
return std::apply(f, x);
}
};
template<int arity, typename FuncType>
DiscreteFun<arity, FuncType> makeDiscreteFun(FuncType&& f)
{
return { std::forward<FuncType>(f) };
}https://stackoverflow.com/questions/56580149
复制相似问题