簡體   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