avoiding code duplication w/ type lists

  • Thread starter =?iso-8859-1?B?RnJhbmstUmVu6SBTY2jkZmVy?=
  • Start date
?

=?iso-8859-1?B?RnJhbmstUmVu6SBTY2jkZmVy?=

-- A class needs to have N members according to N types
mentioned in a typelist (possibly with one type occuring more than
once).
-- The classes should be generated **avoiding** multiple inheritance
(avoiding prosperation of virtual func tables).
-- At the same time, a class taking N types shall contain a virtual
member function that calls a function according to the number
of arguments

That means, something like:

template <typename TL>
struct X {
X(...how?...)

virtual void process(...how?...)
{
function(...how?...);
}

typedef linear_generator<TL> content;
};

How can code duplication be avoided here?
What is the most elegant way to do this?
Should 'X' be itself the generator?

I would be interested in the boost::mpl-way of doing it.
Thanks for any ideas.

Frank
 
M

Martin Eisenberg

Frank-René Schäfer said:
-- A class needs to have N members according to N types
mentioned in a typelist (possibly with one type occuring more
than once).
-- The classes should be generated **avoiding** multiple
inheritance (avoiding prosperation of virtual func tables).
-- At the same time, a class taking N types shall contain a
virtual member function that calls a function according to
the number of arguments

Calls a function on what according to whose arguments? Please make
clearer what process() is supposed to do.
That means, something like:

template <typename TL>
struct X {
X(...how?...)

virtual void process(...how?...)
{
function(...how?...);
}

typedef linear_generator<TL> content;
};

What's the constructor to do with it? Apparently you have some idea
what you might put in the marked places but don't like it -- what is
that?
How can code duplication be avoided here?
What is the most elegant way to do this?
Should 'X' be itself the generator?

I would be interested in the boost::mpl-way of doing it.

I have some code at hand that does something similar. I'm including a
pared-down version below, sorry it's still long. It does not work
with duplicates in the typelist, however.

#include <iostream>
#include <cassert>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/next_prior.hpp>
#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/find.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/static_assert.hpp>

struct ParameterBase {
virtual ~ParameterBase() {}
virtual void updateValue() = 0;
};

template<class T>
struct Parameter : ParameterBase {
typedef T value_type;
virtual void updateValue() { value_ = value_type(5); }
value_type value() const { return value_; }
Parameter() : value_() {}
private:
value_type value_;
};

namespace detail {

template<class Begin, class End = void>
class ParamInstances // Case End != void.
: ParamInstances<typename boost::mpl::next<Begin>::type, End>
{
typedef ParamInstances<typename boost::mpl::next<Begin>::type, End> Base;
typedef typename boost::mpl::deref<Begin>::type P;
P p_;
public:
ParamInstances(ParameterBase* pointers[])
: Base(pointers + 1), p_()
{ *pointers = &p_; }

ParamInstances(ParameterBase* pointers[],
const ParameterBase* const others[])
: Base(pointers + 1, others + 1), p_(static_cast<const P&>(**others))
{}
};

template<class End>
struct ParamInstances<End, End> {
ParamInstances(ParameterBase*[]) {}
ParamInstances(ParameterBase*[], const ParameterBase* const[]) {}
};

template<class ParamTypes>
class ParamInstances<ParamTypes, void>
: ParamInstances<
typename boost::mpl::begin<ParamTypes>::type,
typename boost::mpl::end<ParamTypes>::type>
{
typedef ParamInstances<
typename boost::mpl::begin<ParamTypes>::type,
typename boost::mpl::end<ParamTypes>::type> Base;
public:
ParamInstances(ParameterBase* pointers[]) : Base(pointers) {}
ParamInstances(ParameterBase* pointers[],
const ParameterBase* const others[])
: Base(pointers, others)
{}

enum { ParameterCount = boost::mpl::size<ParamTypes>::value };

template<class P>
class Index {
typedef typename boost::mpl::find<ParamTypes, P>::type Pos;
BOOST_STATIC_ASSERT((!boost::is_same<Pos,
typename boost::mpl::end<ParamTypes>::type>::value));
public:
enum { value = boost::mpl::distance<
typename boost::mpl::begin<ParamTypes>::type, Pos>::value };
};
};

} // namespace detail

template<class ParamTypes>
class Program : detail::paramInstances<ParamTypes> {
typedef detail::paramInstances<ParamTypes> Base;
ParameterBase* params_[Base::parameterCount];
public:
using Base::parameterCount;

Program() : Base(params_) {}
Program(const Program& other) : Base(params_, other.params_) {}

ParameterBase& Program::get(int index) const
{
assert(index < ParameterCount);
return *params_[index];
}

template<class P>
P& get() const
{ return static_cast<P&>(get(Base::template Index<P>::value)); }
};

int main()
{
Program<boost::mpl::vector<Parameter<int>, Parameter<float> > >
myProgram;
std::cout << myProgram.get<Parameter<float> >().value() << ' ';
myProgram.get(1).updateValue();
std::cout << myProgram.get<Parameter<float> >().value();

{ char c; std::cin >> c; }
return 0;
}
 
?

=?iso-8859-1?B?RnJhbmstUmVu6SBTY2jkZmVy?=

The idea was to have something that represents
a list of arguments, i.e.


template <typename TL>
struct X {
// such a constructor is convinient for initialization
X(/*general form of: T0 x0, T1 x1, T2 x2, ...*/) ...

virtual void process() // yes can be empty
{
function(/*a general form of: content.x0, content.x1,
content.x2*/);
}

typedef linear_generator<TL> content;

};
 
M

Martin Eisenberg

Frank-René Schäfer said:
The idea was to have something that
represents a list of arguments, i.e.
[snip example pseudocode]

First of all, thanks for focusing me on this problem! I certainly
have use for the result. Note that if you end up using the code
you'll probably want to add at least non-const access. Before I
explain the code, here's the achieved initialization syntax:

typedef mpl::vector<V, int, int, TempTest> Types;
X<Types> x(tltools::Arguments<Types>(V(3, 2.5))(7)()(1));

The code starts out with the "library" part in namespace tltools,
containing the Arguments and Instantiator facilities. Instantiator
corresponds to your linear_generator; I used a different name to
avoid confusion in case you have already implemented the latter.
After that those facilities' use is demonstrated.

Both the Arguments and Instantiator class templates work in the same
basic way: they build an inheritance chain of template instantiations
from a typelist, with a node for each element type, using the primary
template except for the innermost base. This is similar to what I
posted before, but this time there is no sentinel class at the end.

Each node of an Arguments chain has a constructor taking the
corresponding type in the typelist. However, this ctor is only used
to pass the first argument with the intent to smooth out the point-
of-use syntax. Any further arguments are passed through the
operator() in the primary template that consequently takes the *base*
argument type and is not present in the template specialization. A
conceptually parameterless ctor is also required of the base, but it
cannot be the default ctor as that would disallow a default parameter
to the pass-in ctor -- hence the dummy parameter.

Argument storage and retrieval is delegated to the specialization
that type-safely encapsulates a void* container. It is also safe for
temporaries because those persist until the end of a statement like
the initialization of x in the code excerpt above. Finally, the
specialization has a conversion back to the outermost type, again for
convenient use. To ensure that this conversion is only used on a
completely filled Arguments structure, the primary template uses
protected inheritance.

Each node of an Instantiator inheritance chain has a field of the
corresponding type in the typelist and lets the user retrieve fields
of subsequent types specified by typelist iterators. It also gives
access to the next node, except that a virtual sentinel follows the
last node; this simplifies defining functions that operate on the
whole structure. Finally, there is the converting constructor from
Arguments for the same typelist.

After this "library" part comes a demonstration of the Arguments and
Instantiator facilities' use, including inductive definition of
functions over the Instantiator structure. The struct TempTest is
just to confirm that the compiler gets temporary lifetime right here.

Please let me know of any improvements you can think of!


Martin


#include <iostream>
#include <numeric>
#include <vector>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/next_prior.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/distance.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_convertible.hpp>

namespace mpl = boost::mpl;

namespace tltools {

template<typename Types>
struct last {
typedef typename mpl::prior<typename mpl::end<Types>::type>::type
type;
};

//-------

namespace detail {
struct Dummy;
typedef const Dummy* DummyPtr;
}

template<typename Types, typename Position = typename
mpl::begin<Types>::type>
struct Arguments
: protected Arguments<Types, typename mpl::next<Position>::type>
{
BOOST_STATIC_ASSERT(!mpl::empty<Types>::value);

typedef typename mpl::next<Position>::type NextPosition;
typedef Arguments<Types, NextPosition> Base;
typedef typename mpl::deref<Position>::type Value;
using Base::get;

Arguments(const Value& value = Value())
: Base(detail::DummyPtr(0))
{ this->template put<Position>(value); }

Base& operator()(const typename Base::Value& value = typename
Base::Value())
{
this->template put<NextPosition>(value);
return *this;
}
protected:
Arguments(detail::DummyPtr) : Base(detail::DummyPtr(0)) {}
};

template<typename Types>
struct Arguments<Types, typename last<Types>::type> {
BOOST_STATIC_ASSERT(!mpl::empty<Types>::value);

typedef typename last<Types>::type Position;
typedef typename mpl::deref<Position>::type Value;

Arguments(const Value& value = Value())
: pointers_(mpl::size<Types>::value)
{ put<Position>(value); }

template<typename Iter>
void put(const typename mpl::deref<Iter>::type& value)
{
pointers_[mpl::distance<
typename mpl::begin<Types>::type, Iter>::value] = &value;
}

template<typename Iter>
const typename mpl::deref<Iter>::type& get() const
{
return *static_cast<const typename mpl::deref<Iter>::type*>
(pointers_[mpl::distance<typename mpl::begin<Types>::type,
Iter>::value]);
}

operator const Arguments<Types>& () const
{ return static_cast<const Arguments<Types>&>(*this); }
protected:
Arguments(detail::DummyPtr) : pointers_(mpl::size<Types>::value)
{}
private:
std::vector<const void*> pointers_;
};

//-------

template<typename Types, typename Position = typename
mpl::begin<Types>::type>
struct Instantiator : Instantiator<Types, typename
mpl::next<Position>::type> {
BOOST_STATIC_ASSERT(!mpl::empty<Types>::value);

typedef typename mpl::next<Position>::type NextPosition;
typedef Instantiator<Types, NextPosition> Base;
typedef typename mpl::deref<Position>::type Value;
Value value;

Instantiator(const Arguments<Types>& arguments)
: Base(arguments), value(arguments.get<Position>())
{}

template<typename Iter>
const Instantiator<Types, Iter>& get(typename boost::disable_if<
boost::is_same<Iter, Position> >::type* dummy = 0)
{ return Base::template get<Iter>(); }

template<typename Iter>
const Instantiator& get(typename boost::enable_if<
boost::is_same<Iter, Position> >::type* dummy = 0)
{ return *this; }

const Base& next() const { return *this; }
};

typedef detail::DummyPtr EndOfInstances;

template<typename Types>
struct Instantiator<Types, typename last<Types>::type>
{
BOOST_STATIC_ASSERT(!mpl::empty<Types>::value);

typedef typename last<Types>::type Position;
typedef typename mpl::deref<Position>::type Value;
Value value;

Instantiator(const Arguments<Types>& arguments)
: value(arguments.get<Position>())
{}

template<typename Iter>
const Instantiator& get()
{
BOOST_STATIC_ASSERT((boost::is_same<Iter, Position>::value));
return *this;
}

EndOfInstances next() const { return 0; }
};

} // namespace tltools

//-----------------------------------------------

double sum(double value)
{ return value; }

template<typename T>
double sum(const std::vector<T>& v)
{ return std::accumulate(v.begin(), v.end(), 0.0,
std::plus<double>()); }

double sum(tltools::EndOfInstances)
{ return 0.0; }

template<typename Types, typename Position>
double sum(const tltools::Instantiator<Types, Position>& instances)
{ return sum(instances.value) + sum(instances.next()); }

template<typename Types>
struct X {
tltools::Instantiator<Types> content;
X(const tltools::Arguments<Types>& arguments) : content(arguments)
{}

virtual double process()
{
typedef typename mpl::begin<Types>::type Begin;
typedef typename mpl::end<Types>::type End;
typedef typename mpl::next<Begin>::type Second;
BOOST_STATIC_ASSERT((!boost::is_same<Second, End>::value));
return sum(content) - sum(content.template get<Second>().value);
}
};

struct TempTest {
int value;
operator int() const { return value; }
TempTest(int value) : value(value) {}
TempTest(const TempTest& other) : value(other.value) {}
~TempTest() { value = 0; }
};

int main() {
typedef std::vector<double> V;
typedef mpl::vector<V, int, int, TempTest> Types;
X<Types> x(tltools::Arguments<Types>(V(3, 2.5))(7)()(1));

std::cout << "Expected 8.5, got " << x.process() << ".\n";
{ char c; std::cin >> c; }
return 0;
}

/* end of code */
 
?

=?iso-8859-1?B?RnJhbmstUmVu6SBTY2jkZmVy?=

Thanks for the input. I myself dived into the Appendix A of Abraham's
and Gurtovoy's Metaprogramming book: "preprocessor metaprogramming"
using this pp library allows
for elegant definitions. The solution is similar to

#define MEMBER_print(z, n, data) T##n _x##n;
#define ARGUMENT_print(z, n, data) T##n X##n
#define MEMBER_ARG_print(z, n, data) _x##n

template <class Policy BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM_PARAMS(N,
typename T)>
struct X <Policy BOOST_PP_COMMA_IF(N)
BOOST_PP_ENUM_PARAMS(BOOST_PP_SUB(N,1), T)>
{
virtual void execute()
{ call(BOOST_PP_ENUM(N, MEMBER_ARG_print, none)); }

BOOST_PP_REPEAT(N, MEMBER_print, ~)
};

The lib provides abilities to trace the lines of macros to the compiler
so debugging is not such a pain. In general, It is not a propper
template
solution. It might not be liked by those having allergies against
#defines.
However, it is elegant, explicit, intuitive, and easy to use.

Best Regards

Frank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top