22

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.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662

1 Answers1

21

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
  • 3,626
  • 2
  • 20
  • 26
  • 5
    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 Jun 24 '10 at 15:05
  • 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 Jun 24 '10 at 15:40
  • 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 Jun 24 '10 at 15:47
  • 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>" in addition to "disable_if::value>". You've got the latter done though. – Edward Strange Jun 24 '10 at 15:48
  • 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. – Edward Strange Jun 24 '10 at 15:56
  • 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 Jun 24 '10 at 16:05
  • 2
    Noah fell into the same trap as I did :) – fredoverflow Jun 24 '10 at 17:28
  • 17
    This can be written more simply as: `template using disable_if = std::enable_if<!B, T>;` – Richard Smith Aug 28 '12 at 08:41
  • 1
    using `std::enable_if<!expression>` in VS2013 seems to cause an unrecoverable compiler error. – Nicolas Holthaus Feb 19 '15 at 21:56