|
Boost Users : |
Subject: [Boost-users] [array] the array that thinks it is a number
From: alfC (alfredo.correa_at_[hidden])
Date: 2010-06-16 03:02:43
I have a bunch of numerical routines in C++ that take and return
boost::arrays,
for example
array<double, 5> strange_function(array<double, 3>);
in another example, one integrates boost::function that takes an array
of size N and returns arrays of size F
The library is pretty general because it works in any number of
dimensions. But it seems to be a syntactic waste to use those general
functions in the cases where the input or the output is a single
number, i.e. one has to use array<double, 1> all over the place, array
constructions or ugly casts.
One option would be to transform all the functions and boost::function
declaration to take arbitrary combinations of double input/ouput and
array input/out
double strange_function(array<double, 3>);
array<double,3> strange_function(double );
(actually strange_function is a template function, so what it really
does depends on the template parameter strange_function<T>)
( Think for example of Mathematica functions that take numbers or
vectors Integrate[{f[x],g[x]},x] or Integrate[f[x],x] )
I come up with a solution that is, instead of working with
boost::array work with a similar type that simply believes it is a
number when the dimension is one, here it is the implementation:
template<size_t Dim>
struct array : boost::array<double, Dim>{
typedef boost::array<double, Dim> base;
array(base const& arr) : base(arr){}
array(double const& d);
operator double&();
operator double const&() const;
};
template<> array<1>::array(double const& d) : base((base){{d}}){}
template<> array<1>::operator double&(){return (*this)[0];}
template<> array<1>::operator double const&() const{return (*this)
[0];}
in this way the array is transformed from and into a number if
requested, and the existing code that uses boost::array still works.
Just wondering for some feedback.
Thank you,
Alfredo
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net