對於某些模板類型名,我想創建一個typedef,它是T :: operator ++()(又名T的預增加運算符)的聲明返回類型。使用重載運算符++的C++ decltype ++(preincrement)
我沒有找到任何明確的在線,但肯定有一些decltype提前preincrement提到。所以我嘗試了一些東西,而唯一真正起作用的東西似乎是一個骯髒的黑客。你覺得這怎麼樣?
struct S { // dummy type to simulate a real one I have
int operator++() { return 0; } // note: return type is not S&
int operator++(int) { return 0; }
};
int main() {
// this works:
typedef decltype(++S()) T1;
// so why doesn't this work?
// error: lvalue required as increment operand
// typedef decltype(++int()) T2;
// this works, but seems dirty:
typedef decltype(++*(int*)nullptr) T3;
typedef decltype(++*(S*)nullptr) T4;
// I also haven't figured out how to disambiguate this,
// though it's moot because int::operator++ is not a thing
// error: ‘S::operator++’ refers to a set of overloaded functions
// typedef decltype(S::operator++) T5;
}
我正在使用GCC 4.6.2。我簡單地嘗試過Clang,但它並不好。
FWIW,你不能用'decltype'做一個''++表達式用於獲取*申報*返回類型 - 它曾經用於一些C++ 11草案,但是發佈的規範不再使用這個工作。所以如果你聲明返回類型爲int const,那麼'decltype'會給你的是'int'而不是'int const'。雖然除了這個人爲的例子,我並沒有意識到獲取*聲明*返回類型和簡單表達式類型(發佈的規範產生的)之間的真正區別。 –
我可以忍受這一點。謝謝你的明確解釋。 –