473,804 Members | 1,971 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic indirection adaptor

Hi,

as a result of my last posting about an adaption class template for
invoking algorithms on a container of iterators or pointers to elements
in another container, I have come up with this code:

#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>

template< typename It, typename Pred >
class indirect_binary : public std::binary_fun ction<It,It,boo l>
{
public:
bool operator() (It lhs, It rhs) const {
return Pred() (*lhs, *rhs);
}
};

int main()
{
typedef std::vector<int > IntVec;
typedef IntVec::iterato r IntVecIt;

std::vector<int > v1;
v1.push_back(5) ;
v1.push_back(2) ;

std::vector<int *> v2;
v2.push_back( &v1[0] );
v2.push_back( &v1[1] );

indirect_binary < int*, std::less<int> > fctor; // note the int*!
std::sort( v2.begin(), v2.end(), fctor );

std::vector<int *>::iterator it = v2.begin();
for( ; it != v2.end(); ++it )
{
std::cout << **it << std::endl;
}
}

Well, it works, output is: 2, 5.
However, you may have noticed that I instantiated the adaptor with int*
instead of IntVecIt. If I do the latter, I get tons of error messages:

deref.cpp: In function `int main()':
deref.cpp:25: error: no matching function for call to `
std::vector<mai n()::IntVecIt, std::allocator< main()::IntVecI t>
::push_back( int*)'
/usr/include/c++/3.3/bits/stl_vector.h:59 6: error: candidates are: void
std::vector<_Tp , _Alloc>::push_b ack(const _Tp&) [with _Tp =
main()::IntVecI t, _Alloc = std::allocator< main()::IntVecI t>]
deref.cpp:26: error: no matching function for call to `
std::vector<mai n()::IntVecIt, std::allocator< main()::IntVecI t>::push_back(

int*)'
/usr/include/c++/3.3/bits/stl_vector.h:59 6: error: candidates are: void
std::vector<_Tp , _Alloc>::push_b ack(const _Tp&) [with _Tp =
main()::IntVecI t, _Alloc = std::allocator< main()::IntVecI t>]
deref.cpp:31: error: conversion from `
__gnu_cxx::__no rmal_iterator<m ain()::IntVecIt *,
std::vector<mai n()::IntVecIt, std::allocator< main()::IntVecI t> > >' to
non-scalar type `__gnu_cxx::__n ormal_iterator< int**, std::vector<int *,
std::allocator< int*> > >' requested
deref.cpp:32: error: no match for 'operator!=' in 'it != std::vector<_Tp ,
_Alloc>::end() [with _Tp = main()::IntVecI t, _Alloc =
std::allocator< main()::IntVecI t>]()'

And another question: Why do I have to take lhs and rhs by value in
operator() ? If I declare it taking const references, it won't compile
either.

I'd be glad for all your input, because I intend to use this template
class pretty often once it is finished, so I want it to be as robust as
possible.

--
Matthias Kaeppler
Jul 23 '05 #1
15 1606
Matthias Kaeppler wrote:
Hi,

as a result of my last posting about an adaption class template for
invoking algorithms on a container of iterators or pointers to elements
in another container, I have come up with this code:

#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>

template< typename It, typename Pred >
class indirect_binary : public std::binary_fun ction<It,It,boo l>
{
public:
bool operator() (It lhs, It rhs) const {
return Pred() (*lhs, *rhs);
}
};

int main()
{
typedef std::vector<int > IntVec;
typedef IntVec::iterato r IntVecIt;

std::vector<int > v1;
v1.push_back(5) ;
v1.push_back(2) ;

std::vector<int *> v2;
v2.push_back( &v1[0] );
v2.push_back( &v1[1] );

indirect_binary < int*, std::less<int> > fctor; // note the int*!
std::sort( v2.begin(), v2.end(), fctor );

std::vector<int *>::iterator it = v2.begin();
for( ; it != v2.end(); ++it )
{
std::cout << **it << std::endl;
}
}

Well, it works, output is: 2, 5.
However, you may have noticed that I instantiated the adaptor with int*
instead of IntVecIt. If I do the latter, I get tons of error messages:
Your comparison operators gets passed already-dereferenced iterators,
not the iterators themselves.
And another question: Why do I have to take lhs and rhs by value in
operator() ? If I declare it taking const references, it won't compile
either.


Strange, I changed your comparison function to:

bool operator() (const It& lhs, const It& rhs) const {

and it worked fine...

Did you mean something else?

Chris
Jul 23 '05 #2
Chris Jefferson wrote:
Your comparison operators gets passed already-dereferenced iterators,
not the iterators themselves.


What do you mean? Isn't IntVecIt in most cases just a typedef for int*
anyway? At least it is on my implementation. So:

bool operator() (It lhs, It rhs) {
return Pred() (*lhs, *rhs);
}

translates to:

bool operator() (int* lhs, int* rhs) {
return Pred() (*lhs, *rhs);
}

I can't see what's wrong with that.

--
Matthias Kaeppler
Jul 23 '05 #3
Matthias Kaeppler wrote:
Chris Jefferson wrote:
Your comparison operators gets passed already-dereferenced iterators,
not the iterators themselves.

What do you mean? Isn't IntVecIt in most cases just a typedef for int*
anyway? At least it is on my implementation. So:


It isn't on my implementation (gcc 3.3.3). Assuming that it is is a big
no-no!

You can however given an iterator into a vector<int> do &*it and get an
int*. I'm not positive this is guaranteed by the standard, I remember
seeing a defect report about it and can't remember if it got accepted.
I've never seen an implementation where it didn't work.

Chris
Jul 23 '05 #4
Chris Jefferson wrote:
Matthias Kaeppler wrote:
Chris Jefferson wrote:
Your comparison operators gets passed already-dereferenced iterators,
not the iterators themselves.


What do you mean? Isn't IntVecIt in most cases just a typedef for int*
anyway? At least it is on my implementation. So:


It isn't on my implementation (gcc 3.3.3). Assuming that it is is a big
no-no!

You can however given an iterator into a vector<int> do &*it and get an
int*. I'm not positive this is guaranteed by the standard, I remember
seeing a defect report about it and can't remember if it got accepted.
I've never seen an implementation where it didn't work.

Chris


Oh, okay. But is the design of the adaptor okay?

--
Matthias Kaeppler
Jul 23 '05 #5
Matthias Kaeppler wrote:
Chris Jefferson wrote:
Matthias Kaeppler wrote:
Chris Jefferson wrote:

Your comparison operators gets passed already-dereferenced
iterators, not the iterators themselves.


What do you mean? Isn't IntVecIt in most cases just a typedef for
int* anyway? At least it is on my implementation. So:


It isn't on my implementation (gcc 3.3.3). Assuming that it is is a
big no-no!

You can however given an iterator into a vector<int> do &*it and get
an int*. I'm not positive this is guaranteed by the standard, I
remember seeing a defect report about it and can't remember if it got
accepted. I've never seen an implementation where it didn't work.

Chris

Oh, okay. But is the design of the adaptor okay?


Yes, it's good :)

Chris
Jul 23 '05 #6
Oh, one more question:
I want it to work with both functors and functions. However,
"overloadin g" a template doesn't seem to work (I tried to replace the
second template argument with a pointer to function returning bool and
taking two It::value_typeS ).
This however, results in a redefinition error. Okay, so I renamed the
template and tried it this way:

template< typename It >
class indirect_binary _fn: public std::binary_fun ction<It,It,boo l>
{
bool (*pred)(It::val ue_type, It::value_type) ;
public:
indirect_binary _fn( bool (*f)(It::value_ type, It::value_type) )
: pred(f) {}
bool operator() (const It& lhs, const It& rhs) const {
return pred(*lhs, *rhs);
}
};

Error:
deref.cpp:17: error: variable declaration is not allowed here
deref.cpp:19: error: variable declaration is not allowed here
deref.cpp: In constructor `indirect_binar y_fn<It>::indir ect_binary_fn() ':
deref.cpp:19: error: class `indirect_binar y_fn<It>' does not have any
field named `pred'

Why am I not allowed to declare that variable?

--
Matthias Kaeppler
Jul 23 '05 #7
Matthias Kaeppler wrote:
Oh, one more question:
I want it to work with both functors and functions. However,
"overloadin g" a template doesn't seem to work (I tried to replace the
second template argument with a pointer to function returning bool and
taking two It::value_typeS ).
This however, results in a redefinition error. Okay, so I renamed the
template and tried it this way:

template< typename It >
class indirect_binary _fn: public std::binary_fun ction<It,It,boo l>
{
bool (*pred)(It::val ue_type, It::value_type) ; This should be:
// to make life easier, use a typedef
typedef bool (*pred_fn)(type name It::value_type,
typename It::value_type) ;

pred_fn pred;
public:
indirect_binary _fn( bool (*f)(It::value_ type, It::value_type) )
: pred(f) {} Also:
indirect_binary _fn(pred_fn f) : pred(f) {} bool operator() (const It& lhs, const It& rhs) const {
return pred(*lhs, *rhs);
}
};


There is a much better solution though, to allow for both functors and
functions to be called if you use the boost library:

template<class BinaryPredicate >
class indirect_binary _fn : public std::binary_fun ction<typename
boost::binary_t raits<BinaryPre dicate>::first_ argument_type,
typename
boost::binary_t raits<BinaryPre dicate>::second _argument_type,
bool> {
private:
typedef typename boost::binary_t raits<BinaryPre dicate> It;

BinaryPredicate pred;

public:
indirect_binary _fn(BinaryPredi cate f) : pred(f) {}
bool operator() (const It& lhs, const It& rhs)const
{ return pred(*lhs, *rhs); }
};

typename boost::binary_t raits<BinaryPre dicate>::first_ argument_type and
its brother second_argument _type allow you to get the argument types for
either a function pointer or an AdaptableBinary Predicate (which you can
get by deriving your functors from std::binary_fun ction). The
definintion is a little spammy I know, but in the end you have a much
more useful indirection functor here.
Jul 23 '05 #8
Kurt Stutsman wrote:
Matthias Kaeppler wrote:
Oh, one more question:
I want it to work with both functors and functions. However,
"overloadin g" a template doesn't seem to work (I tried to replace the
second template argument with a pointer to function returning bool and
taking two It::value_typeS ).
This however, results in a redefinition error. Okay, so I renamed the
template and tried it this way:

template< typename It >
class indirect_binary _fn: public std::binary_fun ction<It,It,boo l>
{
bool (*pred)(It::val ue_type, It::value_type) ;


This should be:
// to make life easier, use a typedef
typedef bool (*pred_fn)(type name It::value_type,
typename It::value_type) ;

pred_fn pred;
public:
indirect_binary _fn( bool (*f)(It::value_ type, It::value_type) )
: pred(f) {}


Also:
indirect_binary _fn(pred_fn f) : pred(f) {}
bool operator() (const It& lhs, const It& rhs) const {
return pred(*lhs, *rhs);
}
};


There is a much better solution though, to allow for both functors and
functions to be called if you use the boost library:

template<class BinaryPredicate >
class indirect_binary _fn : public std::binary_fun ction<typename
boost::binary_t raits<BinaryPre dicate>::first_ argument_type,
typename
boost::binary_t raits<BinaryPre dicate>::second _argument_type,
bool> {
private:
typedef typename boost::binary_t raits<BinaryPre dicate> It;

BinaryPredicate pred;

public:
indirect_binary _fn(BinaryPredi cate f) : pred(f) {}
bool operator() (const It& lhs, const It& rhs)const
{ return pred(*lhs, *rhs); }
};

typename boost::binary_t raits<BinaryPre dicate>::first_ argument_type and
its brother second_argument _type allow you to get the argument types for
either a function pointer or an AdaptableBinary Predicate (which you can
get by deriving your functors from std::binary_fun ction). The
definintion is a little spammy I know, but in the end you have a much
more useful indirection functor here.


Nice, thanks for the great advice. I have already lots of boost'ed code
in my program, so I certainly don't mind to add some more.

I'll report back if still something shouldn't work :)

--
Matthias Kaeppler
Jul 23 '05 #9
Matthias Kaeppler wrote:
Kurt Stutsman wrote:
Matthias Kaeppler wrote:
Oh, one more question:
I want it to work with both functors and functions. However,
"overloadin g" a template doesn't seem to work (I tried to replace the
second template argument with a pointer to function returning bool
and taking two It::value_typeS ).
This however, results in a redefinition error. Okay, so I renamed the
template and tried it this way:

template< typename It >
class indirect_binary _fn: public std::binary_fun ction<It,It,boo l>
{
bool (*pred)(It::val ue_type, It::value_type) ;

This should be:
// to make life easier, use a typedef
typedef bool (*pred_fn)(type name It::value_type,
typename It::value_type) ;

pred_fn pred;
public:
indirect_binary _fn( bool (*f)(It::value_ type, It::value_type) )
: pred(f) {}

Also:
indirect_binary _fn(pred_fn f) : pred(f) {}
bool operator() (const It& lhs, const It& rhs) const {
return pred(*lhs, *rhs);
}
};


There is a much better solution though, to allow for both functors and
functions to be called if you use the boost library:

template<class BinaryPredicate >
class indirect_binary _fn : public std::binary_fun ction<typename
boost::binary_t raits<BinaryPre dicate>::first_ argument_type,
typename
boost::binary_t raits<BinaryPre dicate>::second _argument_type,
bool> {
private:
typedef typename boost::binary_t raits<BinaryPre dicate> It; Spotted an error in my code. The above line should be:
typedef typename boost::binary_t raits<BinaryPre dicate>::first_ argument_type It;
BinaryPredicate pred;

public:
indirect_binary _fn(BinaryPredi cate f) : pred(f) {}
bool operator() (const It& lhs, const It& rhs)const
{ return pred(*lhs, *rhs); }
};

typename boost::binary_t raits<BinaryPre dicate>::first_ argument_type
and its brother second_argument _type allow you to get the argument
types for either a function pointer or an AdaptableBinary Predicate
(which you can get by deriving your functors from
std::binary_fun ction). The definintion is a little spammy I know, but
in the end you have a much more useful indirection functor here.

Nice, thanks for the great advice. I have already lots of boost'ed code
in my program, so I certainly don't mind to add some more.

I'll report back if still something shouldn't work :)

Jul 23 '05 #10

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

Similar topics

4
2510
by: Scott Smedley | last post by:
Hi all, I'm trying to write a special adaptor iterator for my program. I have *almost* succeeded, though it fails under some circumstances. See the for-loop in main(). Any pointers/help would be muchly appreciated. Apologies for the long post - I couldn't find a shorter way to
3
2270
by: Stanislaw Salik | last post by:
Hi, Lets suppose we want to use generic algotithms on collections of pointers (both raw and smart). For example, we want to sort a vector of (smart)pointers. We need a comparator that will take two pointers and return a bool. std::vector<std::string *> v; std::sort(v.begin(), v.end(), std::less<int>());
3
2485
by: Matthias Kaeppler | last post by:
Hello, I need to sort a range of pointers with a predicate which applies to the pointees. I tried to use boost::indirect_iterator, however, this will sort the container with the pointees instead the one with the pointers: vector<int> coll; // ... vector<int*> ptrcoll; // ...
1
3303
by: Tony Johansson | last post by:
Hello! I'm reading about design pattern adaptor in the GOF book and there is something that sounds strange. When you use the adaptor design pattern you have these participants. *Target - defines the domain-specific interface that Client uses. * Client
0
2596
by: Tony Johansson | last post by:
Hello!! This is about the adaptor design pattern. If you use the class adaptor its easy to override. It says an object adaptor makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather then the Adaptee itself. What does this mean? Can you give some easy exaples if you have some?
2
1410
by: 3nc0d3d | last post by:
I have needed to cast a pointer with different types for get a value. I have try to use generic, but there are cast exception. For example the following method: generic<typename T> void XClass::GetValue(T gValue) { int iValue=34234234; void *vValue=&iValue; gValue=(T)*vValue;
9
12856
by: mps | last post by:
I want to define a class that has a generic parameter that is itself a generic class. For example, if I have a generic IQueue<Tinterface, and class A wants to make use of a generic class that implements IQueue<Tfor all types T (so it can make use of queues of various object types internally). As useful as this is, it doesn't seem possible. The natural (but illegal) notation would be something like class A<QueueClasswhere QueueClass :...
7
3386
by: juerg.lemke | last post by:
Hi everyone I am interested in having multiple functions with different prototypes and deciding, by setting a pointer, which of them to use later in the program. Eg: int f1(void); char* f2(int);
3
10829
by: imaloner | last post by:
I am posting two threads because I have two different problems, but both have the same background information. Common Background Information: I am trying to rebuild code for a working, commercially sold application with only partial build instructions. The previous maintainer of the code (a mixture of C and C++) is no longer with the company, but when he built the code he used MSVC++, and though I am not certain of the version he was ...
0
9711
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9593
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10343
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10335
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9169
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7633
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.