Reputation: 2765
I have a class MyClass
, which will use either min()
or max()
based on what argument is taken during construction,
class MyClass {
private:
myfunc;
public:
MyClass(args);
}
Later myfunc
will be used in another method in MyClass
, and I would like args
can be used to initialize myfunc
to be either max
or min
, wondering how to achieve that? or maybe other way I can set myfunc
to be either max
or min
will be fine too.
Upvotes: 1
Views: 522
Reputation: 21936
I would do it like this:
class MyClass
{
const bool isMax;
public:
MyClass( bool ax ) : isMax( ax ) { }
template<class E>
E apply( E a, E b ) const
{
if( isMax )
return std::max( a, b );
else
return std::min( a, b );
}
};
Technically doable with a function pointer, or std::function
, however these are probably slower. They compile into indirect jumps. This version compiles into a regular branch. Because the flag never changes, from the CPU’s point of view the outcome is very predictable.
Upvotes: 3