Jump to content

Can conditions be parameters?

- - - - -

  • Please log in to reply
2 replies to this topic

#1
TCristoforo

TCristoforo

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
Let's say I have to evaluate multiple types of conditions

if(A > B), if(A >= B)

and the opposites

if(A < B), if(A <= B)

Is there a way in C++ to pass the relational operators as parameters themselves, so that I might be able to have a function that looks something like the following

function name (argument B) <---this is not a bool value
{
if(B)
{
//run code here
}
}

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
The Boost library has some support for passing strings that represent an expression.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
julmuri

julmuri

    Programmer

  • Members
  • PipPipPipPip
  • 139 posts
Sounds like you could use function objects.
#include <functional>


template < class Pred >
void foo( int a, int b, Pred pred )
{
    bool result = pred( a, b );

    if ( result )
    {
        //
        // run code
    } // if    
}

int main( int argc, char* argv[] )
{
    int a = 0, b = 1;

    //
    // run code if a < b
    foo( a, b, std::less<int>() );

    //
    // run code if a > b
    foo( a, b, std::greater<int>() );

    return 0;
}

Functional defines some generic ones, but you can create your own if need be.
std::string s("oberq zhpu?");std::for_each(s.begin(),s.end(),[&](char&c){c=~c;c=~c-0x01/(~(c|0x20)/0x0D*0x02-0x0B)*0x0D;});std::cout<<s;




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users