使用Enable_if选择成员函数

时间:2016-05-20 11:22:12

标签: templates c++11

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

#include <iostream>
#include <type_traits>
using namespace std;

template<int t>
struct A
{
    template<typename EqualTwo>
    void test();
};

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

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

int main() {
    A<5> five;
    A<2> two;
    cout << five.test() << endl;
    cout << two.test() << endl;
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您的代码搞砸了,可能您想要做的是以下内容:

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

main()

int main() {
  A<5> five;
  A<2> two;
  five.test();
  two.test();
}

Live Demo

编辑:

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

但您可以执行以下操作:

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