|
Boost Users : |
Subject: Re: [Boost-users] [enable_if] How to enable a constructor
From: Noah Roberts (roberts.noah_at_[hidden])
Date: 2011-03-29 12:51:22
On 3/29/2011 2:51 AM, Michael Kaes wrote:
> I want that the first Ctor is only available when a NullType is passed
> in and if not that the second one is available but not the first.
> I don't want to do a class specialization because the class is rather
> big and extracting all the methods to a common class would be
> difficult.
> So how can I reuse the template parameter U for the Ctors enable_if?
> Or is this simply not possible?
For cases like this you do not actually need to enable/disable your
constructor using enable_if or friends. Remember, a member of a
template class is not instantiated if it is not used. Thus...
struct nil_ {};
struct test {};
struct non_nil {};
#include <type_traits>
template < typename T, typename U = nil_ >
struct tstruct
{
tstruct(int)
{
static_assert( std::is_same<U,nil_>::value, "U must be nil." );
}
tstruct(int,int)
{
static_assert( !std::is_same<U,nil_>::value, "U must not be nil." );
}
};
int main()
{
tstruct<test>(1);
tstruct<test,non_nil>(1,2);
tstruct<test>(1,2); // C2338: U must not be nil.
}
The first two lines work fine and the program compiles without the
third. The third though results in error.
You won't be able to write metafunctions to test for the availability of
such functions since they are, in fact, available...but if all you
really want is to disallow certain functions when the instantiation
types match some criteria then this does it.
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