Simplification of patterns

I am new to C ++ (using C ++ 2011) and I would like to find a solution to the following problem. I have a class that is a fonction:

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

I use this object to pass this function to the algorithm represented by the class:

template <int n, typename Functor>
class Algorithm {
private:
    Functor f;
    std::array<double, n> a;
public:
    ...
}

Then i create an object

Algorithm<3, Curve> solver;

But 3, obviously, is 3 coming from the size of the array returned by the method value of any object of type Curve. I would like to simplify this code so that I can use:

Algorithm<Curve> solver;

But I have no idea how to do this. Could you give me a hint?

Regards, Francois

+4
source share
3 answers

Add a member array_lengthor something similar to classes 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();
}

.

+8

"" 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;
+1

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:
    // ...
};

or if you ever want to use functions of a different type - say, intor long longor something else - you can request a return type f.valuewhen called with a default value of any type of its argument :

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

Source: https://habr.com/ru/post/1546272/


All Articles