Templates 使用Enable_if选择成员函数

Templates 使用Enable_if选择成员函数,templates,c++11,Templates,C++11,我有一个类,我需要根据模板中提供的值执行不同的操作。但我收到一条错误消息“prototype与类中的任何原型都不匹配…” #包括 #包括 使用名称空间std; 模板 结构A { 模板 无效试验(); }; 模板 模板 void A::test() { cout您的代码乱七八糟,您可能需要执行以下操作: template<int t, typename Enable = void> struct A; template<int t> struct A<t, type

我有一个类,我需要根据模板中提供的值执行不同的操作。但我收到一条错误消息“prototype与类中的任何原型都不匹配…”

#包括
#包括
使用名称空间std;
模板
结构A
{
模板
无效试验();
};
模板
模板
void A::test()
{

cout您的代码乱七八糟,您可能需要执行以下操作:

template<int t, typename Enable = void>
struct A;

template<int t>
struct A<t, typename std::enable_if<t == 2>::type> {
  void test() { cout << "T is equal to two." << endl; }
};

template<int t>
struct A<t, typename std::enable_if<t != 2>::type> {
  void test() { cout << "T is not equal to two." << endl; }
};
template<int t>
struct A {
  void test() {
    if(t == 2) {
      cout << "T is equal to two." << endl;
    } else {
      cout << "T is not equal to two" << endl;
    }
  }
};

编辑:

不幸的是,除非专门化类本身,否则不能专门化模板类的成员函数

但是,您可以执行以下操作:

template<int t, typename Enable = void>
struct A;

template<int t>
struct A<t, typename std::enable_if<t == 2>::type> {
  void test() { cout << "T is equal to two." << endl; }
};

template<int t>
struct A<t, typename std::enable_if<t != 2>::type> {
  void test() { cout << "T is not equal to two." << endl; }
};
template<int t>
struct A {
  void test() {
    if(t == 2) {
      cout << "T is equal to two." << endl;
    } else {
      cout << "T is not equal to two" << endl;
    }
  }
};
模板
结构A{
无效测试(){
如果(t==2){

在我的真实代码中,而不是在示例中,我有许多其他成员变量和函数不需要专门化。只有这一个函数。没有办法在这一个函数之间切换吗?@JadziaMD您也可以使用继承:一个具有公共代码的基类和您需要的任意多个派生类。请参阅基于主要答案