Boost logo

Boost :

Subject: Re: [boost] enable_if and non-template member functions?
From: Matt Calabrese (rivorus_at_[hidden])
Date: 2011-08-06 15:40:30


On Sat, Aug 6, 2011 at 4:38 AM, John Maddock <boost.regex_at_[hidden]> wrote:

> Folks, I have a problem with enable_if: it works just dandy for template
> member functions in my class, but I have some *non-template* member
> functions and constructors that I want to enable only if the template is
> instantiated with template args that meet certain criteria. Seems like I
> can't do this with enable_if as it then generates an invalid class
> definition. I guess I could use base classes, and/or partial
> specialization, but both involve a lot of code duplication I'd rather not
> have. Anyone any ideas?
>
> Thanks, John.
>

C++0x has a simple answer to this -- default function template template
arguments. This works with constructors and even conversion operators. I
added documentation for this kind of usage to trunk back in April or so, but
I guess it never made it into Release. A quick example of what you can do in
0x:

///////////////////////////
class foo
{
  typedef double value_type;

  template< class A = int
          , typename enable_if_c
            < sizeof( A ) != 0
              && your_arbitrary_condition< value_type >::value
            , int
>::type = 0
>
  foo()
  { /* some constructor enabled only if value_type meets the condition */ }
};
///////////////////////////

There are two sort of subtle things here. First, the sizeof( A ) != 0 part
is to force the condition to be dependent on a template argument. The other
subtle thing is that the second template argument is a non-type template
argument. It was suggested that a macro should be made to hide the
subtleties and make things more concise. In this situation it seems like it
would simplify things a lot. I'll put something together and make sure it
all gets to Release.

-- 
-Matt Calabrese

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk