0

I know these two topics have been discussed before, but I still don't have a clear idea of how enable of a constructor and enable of a method works.

Here is a nice clear example that I created.

#include <type_traits>
#include <string>
#include <iostream>



template<bool B> using EnableConstructorIf = typename std::enable_if<B, int>::type;

template<bool B, class T> using EnableMethodIf = typename std::enable_if<B,T>::type;


template <int N>
class MyClass {
public:
  std::string s;


  template<int M=N, EnableConstructorIf< (M<0) > = 0> MyClass() {
    s = "Negative";
  }
  template<int M=N, EnableConstructorIf< (M==0) > = 0> MyClass() {
    s = "Zero";
  }
  template<int M=N, EnableConstructorIf< (M>0) > = 0 > MyClass() {
    s = "Positive";
  }

  template<int M=N> EnableMethodIf< (M<0),  int> getSign() {
    return -1;
  }
  template<int M=N> EnableMethodIf< (M==0), int> getSign() {
    return 0;
  }
  template<int M=N> EnableMethodIf< (M>0),  int> getSign() {
    return +1;
  }


};



int main(int argc, char *argv[])
{
  using namespace std;

  MyClass<-5> a;
  MyClass<0> b;
  MyClass<100> c;

  cout << "a.string = " << a.s <<" ->"<< a.getSign() << endl;
  cout << "b.string = " << b.s <<" ->"<< b.getSign() << endl;
  cout << "c.string = " << c.s <<" ->"<< c.getSign() << endl;


  return 0;
}

It compiles and produces the following output, as expected. But how does it work?

a.string = Negative ->-1
b.string = Zero ->0
c.string = Positive ->1
RFS
  • 311
  • 3
  • 8
  • 1
    Please specify what specifically is unclear that wasn't answered already by other questions on `enable_if`. Otherwise I don't see any reason not to close the question as duplicate. – walnut Nov 21 '19 at 02:21
  • @uneven_mark It's not well written. – RFS Nov 21 '19 at 02:23
  • @uneven_mark First off, my code is clear, concise, pedagogical, and it actually compiles and runs as expected. Second, it gives examples of both constructor and method enable in the same question.You're saying that this question would not help anyone, not a single person? – RFS Nov 21 '19 at 02:26
  • What is wrong with [this question from the C++ FAQ](https://stackoverflow.com/questions/3407633/explain-c-sfinae-to-a-non-c-programmer/3407694)? I never said that your question doesn't help anyone. It seems you intend this to be used as a reference question and that you are not actually looking for an answer for yourself. That was not obvious to me and a question being marked duplicate does not prevent it from helping others find answers. – walnut Nov 21 '19 at 02:39
  • uneven_mark I printed it out. I'll read it in the morning. – RFS Nov 21 '19 at 02:42
  • Possible duplicate of [Select class constructor using enable\_if](https://stackoverflow.com/questions/17842478/select-class-constructor-using-enable-if) – NicholasM Nov 21 '19 at 04:58

0 Answers0