模板参数简化

Template parameters simplification

本文关键字:参数      更新时间:2023-10-16

我对c++相当陌生(使用c++ 2011),我想为以下问题找到解决方案。我有一个表示函数的类:

class Curve {
private:
    ...
public:
    std::array<double, 3> value(double s);
}

我使用该对象将这个函数传递给一个算法,该算法由一个类表示:

template <int n, typename Functor>
class Algorithm {
private:
    Functor f;
    std::array<double, n> a;
public:
    ...
}
然后创建对象
Algorithm<3, Curve> solver;

但是3显然是来自于任何Curve类型对象的方法值所返回的数组的大小。我想简化这段代码,以便我可以使用:

Algorithm<Curve> solver;

但是我不知道该怎么做。你介意给我个提示吗?

最诚挚的问候,弗朗索瓦

添加成员array_length或类似Curve的类:

class Curve
{
public:
    static constexpr const std::size_t length = 3;
private:
    std::array<double,length> a;
};
template<typename ALGORITHM , std::size_t n = ALGORITHM::length>
class Algorithm
{
    ...
};

如果你需要允许经典函数实体作为算法,这种方法不起作用,因为没有length成员。另一种方法是创建一个元函数data_length给定一个算法函数F,返回数据的长度:

template<typename F>
struct length;
//Specialization for Curve class:
template<>
struct length<Curve> : public std::integral_constant<std::size_t,3>
{};

然后:

template<typename F , std::size_t n = length<F>::value>
struct Algorithm
{
   ...
};

EDIT:与其他模板一样,要实现该方法,请指定其模板参数:

template<typename F , std::size_t N>
void Algorithm<F,N>::execute()
{
    _f();
}

使用decltype来获取value的返回类型,使用std::tuple_size来查看它的大小(Live at Coliru):

template <typename Functor>
class Algorithm {
private:
    Functor f;
    static const std::size_t n =
      std::tuple_size<decltype(f.value(0.))>::value;
    std::array<double, n> a;
public:
    // ...
};

或者如果您只是希望a具有与value返回的相同类型:

template <typename Functor>
class Algorithm {
private:
    Functor f;
    decltype(f.value(0.)) a;
public:
    // ...
};

或者如果有一天你想使用不同类型的函数——比如intlong long或其他类型的函数——你可以在调用f.value时使用默认构造值(无论它的参数类型是什么)来请求返回类型:

template <typename Functor>
class Algorithm {
private:
    Functor f;
    decltype(f.value({})) a;
public:
    // ...
};

你可以像这样在枚举成员中"传递" 3:

class Curve {
public:
   enum { arity = 3 };
   std::array<double, arity> value(double s);
};
template <typename Functor>
class Algorithm {
private:
   std::array<double, Functor::arity> a;
};
Curve curve;
Algorithm<Curve> solver;