模板[部分]功能专业化 - 编译时的确定

时间:2016-02-27 22:11:03

标签: c++

有没有办法让以下功能起作用?

enum Color { RED, GREEN, BLUE };

struct Red {
  int myVar { 1 };
};

struct Green {
    int myOtherVar { 2 };
};

struct Blue {
  int myLastVar { 3 };
};

template <typename T>
struct MyStruct {
  template <typename PassIn, Color color>
  void method(PassIn );
};

template <typename T>
template <typename PassIn, Color color>
void MyStruct<T>::method(PassIn passIn) {
  switch (color) {
    case RED:
      cout << passIn.myVar << " RED" << endl;
      break;
    case GREEN:
      cout << passIn.myLastVar << " BLUE" << endl;
      break;
    case BLUE:
      cout << passIn.myOtherVar << " GREEN" << endl;
      break;
  }
}

int main() {
  MyStruct<int> myStruct;
  Red red;
  Green green;
  Blue blue;
  myStruct.method<Red, RED>(red);
  myStruct.method<Green, GREEN>(green);
  myStruct.method<Blue, BLUE>(blue);
  return 0;
}

基本上,我希望'color'参数告诉'method''passIn'变量是什么类型的结构(无论是'myVar','myOtherVar'还是'myLastVar')。有没有办法解决这个问题?

0 个答案:

没有答案