For a non template member function foo of the above , i want to have
any one
of the two brunch code executed.
template<typename T,typename P,bool m>
class my_class
{
void foo()
{
if(m)
{
execute first branch.
}
else
{
execute second branch.
}
}
};
as a present it uses runtime if/else to go to either first branch or
second branch with the hope that
as the compiler knows the value of m at the compile time, it can
eliminate the dead branch.
i can't use enable if as foo is a non template member (or any way it
can be done ?)
i can't use member specialization (directly) as my_class itself is a
template. In that case i have to take help of another helper class.
mpl if is another option , like if_<m,branch1,branch2>::type::execute
();
but again , i have to write a few classes , make some friends for
internal data access etc.
is there any simpler option (like D static if ?) exists ? ot which
one is the best option ?
thanks
abir
There is the solution of function overloading from Andrei Alexandrescu
(Modern C++). You create a type BoolToType<bool> and use it to create
overloaded functions:
template<bool>struct BoolToType{};
template<typename T,typename P,bool m>
class my_class
{
void foo()
{
return foo(BoolToType<m>());
}
void foo(const BoolToType<true>&)
{
execute first branch.
}
void foo(const BoolToType<false>&)
{
execute second branch.
}
};
--
Michael