繁体   English   中英

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

[英]Template specialization for a compile-time constant integer

是否可以专门化一个函数(或至少一个类)来在常量(编译时!)整数和所有其他参数之间进行选择? 如果是这样,那么仅对特定常量值进行specialize(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;
}

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

要在示例中获取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; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM