编译时常量整数的模板特化

时间:2012-11-16 19:16:52

标签: c++ templates gcc c++11

是否可以专门化一个函数(或至少一个类)来在常量(编译时!)整数和所有其他参数之间进行选择?如果是这样,那么对特定常量值进行专门化(enable_if)会很好。

在下面的示例中,这将意味着输出“var”,“const”和“var”,而不是三个“var”。

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

struct test
{
    template <typename T>
    test& operator=(const T& var) { cout << "var" << endl; return *this; }
    template <int n> // enable_if< n == 0 >
    test& operator=(int x) { cout << "const" << endl; return *this; }
};

int main()
{
    test x;
    x = "x";
    x = 1;
    int y = 55;
    x = y;
    return 0;
}

UPDATE:编辑代码以强调它必须是编译时常量。

1 个答案:

答案 0 :(得分:3)

要在示例中获得var, const, var,您可以这样做。

struct test {
  template <typename T>
  test& operator=(const T& var) { cout << "var" << endl; return *this; }
  test& operator=(int &&x) { cout << "const" << endl; return *this; }
};

它适用于所有临时工,但它会失败:

const int yy = 55;
x = yy;

为了使它适用于这种情况,你需要添加:

test& operator=(int &x)       { cout << "var" << endl; return *this; }
test& operator=(const int &x) { cout << "const" << endl; return *this; }
相关问题