首页 > 解决方案 > C++ 此代码如何工作(enable_if 构造函数/方法)?

问题描述

我知道这两个主题之前已经讨论过,但是我仍然不清楚构造函数的启用和方法的启用是如何工作的。

这是我创建的一个很好的清晰示例。

#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;
}

正如预期的那样,它编译并产生以下输出。但它是如何工作的?

a.string = Negative ->-1
b.string = Zero ->0
c.string = Positive ->1

标签: c++sfinaeenable-if

解决方案


推荐阅读