1

関数 (または少なくともクラス) を特殊化して、定数 (コンパイル時!) 整数と他のすべての引数を選択することは可能ですか? その場合は、特定の定数値のみに特化 (enable_if) するとよいでしょう。

以下の例では、これは 3 つの「var」ではなく、出力「var」、「const」、および「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;
}

更新: コードを編集して、コンパイル時に一定でなければならないことを強調しました。

4

1 に答える 1

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; }
于 2012-11-16T19:42:11.247 に答える