473,566 Members | 2,847 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_generato r<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 3629
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_generato r<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.h pp>

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::nex t<Begin>::type , End>
{
typedef ParamInstances< typename boost::mpl::nex t<Begin>::type , End> Base;
typedef typename boost::mpl::der ef<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::beg in<ParamTypes>: :type,
typename boost::mpl::end <ParamTypes>::t ype>
{
typedef ParamInstances<
typename boost::mpl::beg in<ParamTypes>: :type,
typename boost::mpl::end <ParamTypes>::t ype> Base;
public:
ParamInstances( ParameterBase* pointers[]) : Base(pointers) {}
ParamInstances( ParameterBase* pointers[],
const ParameterBase* const others[])
: Base(pointers, others)
{}

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

template<class P>
class Index {
typedef typename boost::mpl::fin d<ParamTypes, P>::type Pos;
BOOST_STATIC_AS SERT((!boost::i s_same<Pos,
typename boost::mpl::end <ParamTypes>::t ype>::value));
public:
enum { value = boost::mpl::dis tance<
typename boost::mpl::beg in<ParamTypes>: :type, Pos>::value };
};
};

} // namespace detail

template<class ParamTypes>
class Program : detail::ParamIn stances<ParamTy pes> {
typedef detail::ParamIn stances<ParamTy pes> Base;
ParameterBase* params_[Base::Parameter Count];
public:
using Base::Parameter Count;

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

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

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

int main()
{
Program<boost:: mpl::vector<Par ameter<int>, Parameter<float > > >
myProgram;
std::cout << myProgram.get<P arameter<float> >().value() << ' ';
myProgram.get(1 ).updateValue() ;
std::cout << myProgram.get<P arameter<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_generato r<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::Argu ments<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_generato r; 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.h pp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_convertible. hpp>

namespace mpl = boost::mpl;

namespace tltools {

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

//-------

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

template<typena me Types, typename Position = typename
mpl::begin<Type s>::type>
struct Arguments
: protected Arguments<Types , typename mpl::next<Posit ion>::type>
{
BOOST_STATIC_AS SERT(!mpl::empt y<Types>::value );

typedef typename mpl::next<Posit ion>::type NextPosition;
typedef Arguments<Types , NextPosition> Base;
typedef typename mpl::deref<Posi tion>::type Value;
using Base::get;

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

Base& operator()(cons t typename Base::Value& value = typename
Base::Value())
{
this->template put<NextPositio n>(value);
return *this;
}
protected:
Arguments(detai l::DummyPtr) : Base(detail::Du mmyPtr(0)) {}
};

template<typena me Types>
struct Arguments<Types , typename last<Types>::ty pe> {
BOOST_STATIC_AS SERT(!mpl::empt y<Types>::value );

typedef typename last<Types>::ty pe Position;
typedef typename mpl::deref<Posi tion>::type Value;

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

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

template<typena me Iter>
const typename mpl::deref<Iter >::type& get() const
{
return *static_cast<co nst typename mpl::deref<Iter >::type*>
(pointers_[mpl::distance<t ypename mpl::begin<Type s>::type,
Iter>::value]);
}

operator const Arguments<Types >& () const
{ return static_cast<con st Arguments<Types >&>(*this); }
protected:
Arguments(detai l::DummyPtr) : pointers_(mpl:: size<Types>::va lue)
{}
private:
std::vector<con st void*> pointers_;
};

//-------

template<typena me Types, typename Position = typename
mpl::begin<Type s>::type>
struct Instantiator : Instantiator<Ty pes, typename
mpl::next<Posit ion>::type> {
BOOST_STATIC_AS SERT(!mpl::empt y<Types>::value );

typedef typename mpl::next<Posit ion>::type NextPosition;
typedef Instantiator<Ty pes, NextPosition> Base;
typedef typename mpl::deref<Posi tion>::type Value;
Value value;

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

template<typena me Iter>
const Instantiator<Ty pes, Iter>& get(typename boost::disable_ if<
boost::is_same< Iter, Position> >::type* dummy = 0)
{ return Base::template get<Iter>(); }

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

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

typedef detail::DummyPt r EndOfInstances;

template<typena me Types>
struct Instantiator<Ty pes, typename last<Types>::ty pe>
{
BOOST_STATIC_AS SERT(!mpl::empt y<Types>::value );

typedef typename last<Types>::ty pe Position;
typedef typename mpl::deref<Posi tion>::type Value;
Value value;

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

template<typena me Iter>
const Instantiator& get()
{
BOOST_STATIC_AS SERT((boost::is _same<Iter, Position>::valu e));
return *this;
}

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

} // namespace tltools

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

double sum(double value)
{ return value; }

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

double sum(tltools::En dOfInstances)
{ return 0.0; }

template<typena me Types, typename Position>
double sum(const tltools::Instan tiator<Types, Position>& instances)
{ return sum(instances.v alue) + sum(instances.n ext()); }

template<typena me Types>
struct X {
tltools::Instan tiator<Types> content;
X(const tltools::Argume nts<Types>& arguments) : content(argumen ts)
{}

virtual double process()
{
typedef typename mpl::begin<Type s>::type Begin;
typedef typename mpl::end<Types> ::type End;
typedef typename mpl::next<Begin >::type Second;
BOOST_STATIC_AS SERT((!boost::i s_same<Second, End>::value));
return sum(content) - sum(content.tem plate get<Second>().v alue);
}
};

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

int main() {
typedef std::vector<dou ble> V;
typedef mpl::vector<V, int, int, TempTest> Types;
X<Types> x(tltools::Argu ments<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: "preprocess or 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_prin t(z, n, data) _x##n

template <class Policy BOOST_PP_COMMA_ IF(N) BOOST_PP_ENUM_P ARAMS(N,
typename T)>
struct X <Policy BOOST_PP_COMMA_ IF(N)
BOOST_PP_ENUM_P ARAMS(BOOST_PP_ SUB(N,1), T)>
{
virtual void execute()
{ call(BOOST_PP_E NUM(N, MEMBER_ARG_prin t, 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
1282
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" nodeset="id" required="true()" type="xsi:slt_code"/>
5
1724
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 they want to despatch from a list of available ones. In many cases, these items will be of the same time, so the dropdown of available serial no's...
20
23067
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 much finer level. As such, it's very frustrating to be working in VBA which lacks inheritance, one of the more powerful tools for eliminating...
2
2318
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 just a bunch of rows and columns - just like in a DataTable or row set returned by a DataReader. You can visualize this as 3 columns and N rows. ...
2
1205
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 way of avoiding a postback with this by maybe retrieving all the data at the start and then filtering what should be displayed on the second dropdown...
12
1399
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 duplicates. And to make it harder (or not???!!) my criteria for defining the duplicate is the left 15 (or so) characters of the file path. Help, as...
7
2005
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 default in textual fields from tables. What would be the style sheet statements to achieve this?
7
5450
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 the link which in the one side and it will load the map on the other and I have to check map is loaded. Any one tell me how do I use Dispatch or any...
2
1577
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 vertices and edges to Graph object and can use it in other functions ,so that my code gets reduced .If yes please help me giving me one example for...
0
7666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8108
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7644
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7951
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6260
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5484
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
925
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.