Trade-offs of templated implementations
Hi All,
I'd like some comments on the pros and cons of three different
approaches of the same simple logic (best practice, code performance,
generated code, etc ...) :
1) Only runtime evaluation.
class MyClass
{
public:
MyClass( bool tof )
: tof_(tof)
{ }
void func0( int i )
{
if(tof_)
{
auto iter = std::lower_bound(ints_.begin(), ints_.end(),
i, std::less<int>());
// ...
}
else
{
auto iter = std::lower_bound(ints_.begin(), ints_.end(),
i, std::greater<int>());
// ...
}
}
private:
bool const tof_;
std::vector<int> ints_;
};
2) Compile-time evaluation.
template< bool ToF >
class MyClass
{
private:
template< typename Tp, bool >
struct Comp
{
bool operator()( Tp const &lhs, Tp const &rhs ) const
{ return lhs < rhs; }
};
template< typename Tp >
struct Comp<Tp,false>
{
bool operator()( Tp const &lhs, Tp const &rhs ) const
{ return lhs > rhs; }
};
public:
void func0( int i )
{
auto iter = std::lower_bound(ints_.begin(), ints_.end(),
i, Comp<int,ToF>());
// ...
};
private:
std::vector<int> ints_;
};
3) Runtime branching based on a compile-time value. I take it most
compilers would remove the useless branch.
template< bool ToF >
class MyClass
{
public:
void func0( int i )
{
if(ToF)
{
auto iter = std::lower_bound(ints_.begin(),
ints_.end(), i, std::less<int>());
// ...
}
else
{
auto iter = std::lower_bound(ints_.begin(),
ints_.end(), i, std::greater<int>());
// ...
}
};
private:
std::vector<int> ints_;
};
Thanks,
Olivier.
P.S: Please discard the use of the 'auto' keyword as defined in C++0x.
I'm just too lazy to write the full type :)
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]