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

G

Gundolf

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
 
V

Victor Bazarov

Gundolf said:
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
 
A

Alf P. Steinbach

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

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

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,173
Latest member
GeraldReund
Top