如何通过class模板的参数指定成员函数(在class内更好)?

How to specify a member function (inside class is better) by the argument of class template?

我有一些class喜欢

enum Type {ONE, TWO};

template <enum Type T>
class A {
    void foo() {}
};

我想根据 class 的模板参数 T 指定函数 foo()。是否可以在 class 内完成?或者,在class之外怎么办?

编辑:

如果我的 class 是

怎么办
template <class U, enum Type T>
class A {
    void foo() {}
};

这个 class 不能简单地通过提供 foo 的两个版本来专门化 我在 What is wrong with partial template specialization? 找到了解决方案 这可能会使代码变得很长。

是否有任何其他解决方案,或者是否应该使用其他设计?

您可以显式特化 class 模板的成员函数。你只需要做:

template <>
void A<ONE>::foo()
{
//ONE stuff
}

或者,您可以使用标记分派。在这种特殊情况下,它们没有多大意义,但如果您的要求略有不同,它们可能会有所不同。

template <enum Type T>
class A
{
public:
  void foo() {fooImpl(std::conditional_t<T==ONE, std::true_type, std::false_type>());}

  void fooImpl(std::true_type)
  {
    cout << "ONE" << endl; 
  }

  void fooImpl(std::false_type)
  {
    cout << "TWO" << endl; 
  }
};

根据上面的定义,

int main()
{
  A<ONE>().foo();
  A<TWO>().foo();
  return 0;
}

打印

ONE
TWO