472,958 Members | 2,088 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 software developers and data experts.

avoiding code duplication w/ type lists

-- 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

Jan 30 '06 #1
4 3592
Frank-René Schäfer wrote:
-- 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;
}
--
Quidquid latine scriptum sit, altum viditur.
Jan 30 '06 #2
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;

};

Jan 30 '06 #3
Frank-René Schäfer wrote:
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 */
Feb 1 '06 #4
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

Feb 1 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Victor Engmark | last post by:
When my XML Schema contains <xsd:sequence> <xsd:element name="id" type="slt_code"/> </xsd:sequence> , I don't want to duplicate this information by having to type <xf:bind id="slotId-bind"...
5
by: CJM | last post by:
In an application I'm working the user has the opportunity to record the despatching of one or more items with serial numbers. For each item they despatch, they have to chose the serial no that...
20
by: Steve Jorgensen | last post by:
A while back, I started boning up on Software Engineering best practices and learning about Agile programming. In the process, I've become much more committed to removing duplication in code at a...
2
by: Guadala Harry | last post by:
I have some logic that currently processes values retrieved by looping through a HashTable/ListDictionary structure (a hash table that contains ListDictionary objects as its values). Logically it's...
2
by: NH | last post by:
Hi, I have two dropdown lists in a web form. When you choose an entry in the first list the code retrieves records from the database and displays them in the second dropdownlist. Is there a...
12
by: google_groups3 | last post by:
Hi all. I currently have 2 text files which contain lists of file names. These text files are updated by my code. What I want to do is be able to merge these text files discarding the...
7
by: onetitfemme | last post by:
Hi, for some reason Firefox is apparently inserting a new line somehow after some IPA symbols which I have written in their hexadecimal notation. Also, I would like to have two spaces by...
7
by: vinthan | last post by:
hi, I am new to python. I have to write test cases in python. An application is open in the desk top ( application writen in .Net) I have to write code to get focuse the application and click on...
2
by: Man4ish | last post by:
My Program is working fine but problem is this it is too lengthy , i am creating Graph object again and again in each function the i am using it .Can I make one Global function in which i can assign...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.