4

I'd like to be able to disable an overloaded operator function based on template parameters like so

template <int T>
 class Foo {
  int v;

  template <std::enable_if_t<T == 0, int> = 0>
  Foo operator-() const
  {
    return {-v};
  }
};

But when I try to instantiate a Foo with a value that would disable the function (i.e. 1) the compiler complains

Foo<0> f0; // This compiles
Foo<1> f1; // This does not

I am not trying to invoke the disabled function but the compile complains about being unable to access it.

Any explanations of this behavior?

Jesse Ryan
  • 73
  • 6
  • SFINAE doesn't work this way. `operator-` should be a template itself with an additional template parameter, and `enable_if_t` should depend on that parameter, not on `T`. Otherwise, you'll have a hard error. See the dupes for details. – Evg Jul 31 '20 at 07:32
  • Thank you. I wasn't aware of those SFINAE evaluation rules. Duplicating the T parameters solves the issue. – Jesse Ryan Jul 31 '20 at 07:40
  • In C++20 we'll be able to write `Foo operator-() const requires(T == 0) {...}` without the need to use SFINAE tricks. – Evg Jul 31 '20 at 07:42

0 Answers0