Feedback on this template function

J

JohanS

I have been trying to create this function for some time now. Reading
about pointers to member functions until my head hurts. Now i did it
like you see below and i am now wondering. What am i missing here?
What am i not thinking about? Cause this way was to easy. Will i get
in trouble in the future doing it this way? Feedback appreciated! Is
there something that can be done alot better (I'm not looking for a
totally different way of doing it)?


#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))

namespace misc {
template <typename Iterator, typename Function>
int count(Iterator start, Iterator end, Function fun, int value)
{
int temp = 0;

while(start != end)
{
if(CALL_MEMBER_FN(*start, fun) () == value)
++temp;

++start;
}

return temp;
}}

// In main -> works.. wohoo
cout << misc::count(vl.begin(), vl.end(),
&SomeClass::SomeMemberFunction, 3);
 
D

David Hilsee

JohanS said:
I have been trying to create this function for some time now. Reading
about pointers to member functions until my head hurts. Now i did it
like you see below and i am now wondering. What am i missing here?
What am i not thinking about? Cause this way was to easy. Will i get
in trouble in the future doing it this way? Feedback appreciated! Is
there something that can be done alot better (I'm not looking for a
totally different way of doing it)?


#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))

namespace misc {
template <typename Iterator, typename Function>
int count(Iterator start, Iterator end, Function fun, int value)
{
int temp = 0;

while(start != end)
{
if(CALL_MEMBER_FN(*start, fun) () == value)
++temp;

++start;
}

return temp;
}}

// In main -> works.. wohoo
cout << misc::count(vl.begin(), vl.end(),
&SomeClass::SomeMemberFunction, 3);

The macro is unnecessary, and macros are generally frowned upon because they
can cause headaches, so consider removing it. Also, you could probably do
the same thing using std::count_if (<algorithm>) and some of the stuff
provided in <functional> or boost's library, but I wouldn't call such an
approach "better" because it can be confusing. I suppose that you could
also make the type of the last parameter a template argument (e.g. "T value"
instead of "int value"), but it's not necessary if you're only dealing with
ints. Is there anything that you do not like about the code?
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top