specialization of member function

A

abir

Hi,
I have a template my_class which has a bool value template parameter
along with several type template parameters.

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
 
M

Michael DOUBEZ

abir said:
Hi,
I have a template my_class which has a bool value template parameter
along with several type template parameters.

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 ?

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

};
 

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,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top