|
Boost Users : |
From: Andrew Holden (aholden_at_[hidden])
Date: 2007-11-27 14:36:30
Hicham Mouline <hicham_at_[hidden]> wrote:
> Is it possible to define some member functions conditionally
> on integral template argument values?
>
> template <int n>
> class C {
> void f1();
> void f2();
> ....
> void f6(); // should be a member only if n==3 for e.g. };
>
> I could specialize this template and then i would have to
> define f1..5() for both the general case and the special case(n==3).
It has been my experience that you don't generally need to worry about
deleting member functions like this. If the body of f6 won't compile
for certain values of the template arguments, and you don't call it for
those arguments, then the compiler won't give an error. If you want to
clean up the error messages for cases where you do try to call it when
you shouldn't, or if it compiles but doesn't make sense, you could put a
BOOST_STATIC_ASSERT at the start of f6's body, next to a comment
explaining what template arguments make the function valid. For
example, this sample program compiles using vc8sp1:
// Begin sample
#include <boost/static_assert.hpp>
template <int n>
struct C
{
void f1()
{
//Force a compiler error if n != 3
BOOST_STATIC_ASSERT (n == 3);
}
};
int main()
{
C<3> c1;
c1.f1();
C<2> c2;
// c2.f1(); //Works fine as long as this line remains
commented out
}
// End sample
If it really is critical that f6 be deleted, then the only way I can
think of is to put it in a base class and use a template metafunction to
conditionally derive class C from that base class or an empty base
class.
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net