views:

216

answers:

1

Boost has both enable_if and disable_if, but C++0x seems to be missing the latter. Why was it left out? Are there meta-programming facilities in C++0x that allow me to build disable_if in terms of enable_if?


Oh, I just noticed that std::enable_if is basically boost::enable_if_c, and that there is no such thing as boost::enable_if in C++0x.

+3  A: 

At the risk of seeming stupid, just do !expression instead of expression in the bool template parameter in enable_if to make it behave like a disable_if? Of course if that idea works, you could just expand on it to write a class with disable_if-like behavior?

Ok, I believe you could implement disable_if like this:

template <bool B, typename T = void>
struct disable_if {
    typedef T type;
};

template <typename T>
struct disable_if<true,T> {
};
Jacob
Yes, I just realized `enable_if` takes a `bool` instead of a type, so negating the condition is trivial. Still, it would make the code more readable to have `disable_if`.
FredOverflow
Ok, I gave writing a disable_if a shot, while I do believe it to be correct, my meta-programming abilities are lacking a bit.
Jacob
Looks good to me (except for the missing semicolon after the `typedef` in line 3). I would probably reverse the logic, i.e. make an empty general `struct` and then specialize that for `false`, but that's just a matter of opinion/style, not correctness :)
FredOverflow
Not quite. Both enable_if and disable_if can take bool metafunctions as the first parameter. For instance, you can write "disable_if< is_same<T,someclass>>" in addition to "disable_if<is_same<T,someclass>::value>". You've got the latter done though.
Noah Roberts
I'm wrong...partially. You've implemented disable_if_c. You can't pass bool values to disable_if, only bool metafunctions. disable_if is of course trivially implemented in terms of disable_if_c.
Noah Roberts
But when I go look up the current C++ draft and look in table 53, enable_if is shown as taking a boolean value like enable_if_c in Boost. So obviously there's a difference there?
Jacob
Noah fell into the same trap as I did :)
FredOverflow