By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,911 Members | 1,134 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,911 IT Pros & Developers. It's quick & easy.

'Passing' an operator like <, >, == to a template function?

P: n/a
Hi,

I'm wondering if there is some neat way of passing a comparative
operator (<, >, = , <=, ...) to a template-style-function.

For starters, I guess we've all seen this neat little example:

template <class T> Min (T x, T y)
{
return x < y ? x : y;
}

Ok, but now suppose I wanted to use the _operator_ (here "<") as a
template instead - or even in addition to - the operand type:

bool template <operator O> comp (int x, int y)
{
return x O y;
}

So, having this I could say something like:
if (comp<=> (x, y)) ...
if (comp<!=> (x, y)) ...
and get the compiler to generate different versions of comp().

Of course I tried it and it doesn't compile :(
Can anybody think of a way of doing this (apart from using macros)?

Thanks,
Gundolf

Aug 1 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Gundolf wrote:
I'm wondering if there is some neat way of passing a comparative
operator (<, >, = , <=, ...) to a template-style-function.

For starters, I guess we've all seen this neat little example:

template <class T> Min (T x, T y)
{
return x < y ? x : y;
}

Ok, but now suppose I wanted to use the _operator_ (here "<") as a
template instead - or even in addition to - the operand type:

bool template <operator O> comp (int x, int y)
{
return x O y;
}

So, having this I could say something like:
if (comp<=> (x, y)) ...
if (comp<!=> (x, y)) ...
and get the compiler to generate different versions of comp().

Of course I tried it and it doesn't compile :(
Can anybody think of a way of doing this (apart from using macros)?


Check out <functional> header and functors 'equal_to', 'not_equal_to', et
cetera.

V
Aug 1 '05 #2

P: n/a
* Gundolf:
I'm wondering if there is some neat way of passing a comparative
operator (<, >, = , <=, ...) to a template-style-function.

For starters, I guess we've all seen this neat little example:

template <class T> Min (T x, T y)
{
return x < y ? x : y;
}

Ok, but now suppose I wanted to use the _operator_ (here "<") as a
template instead - or even in addition to - the operand type:

bool template <operator O> comp (int x, int y)
{
return x O y;
}

So, having this I could say something like:
if (comp<=> (x, y)) ...
if (comp<!=> (x, y)) ...
and get the compiler to generate different versions of comp().


See std::equal_to and friends.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 1 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.