c – 可以使用成員函式呼叫作為預設引數嗎?
這是我的程式碼:
struct S { int f() { return 1; } int g(int arg = f()) { return arg; } }; int main() { S s; return s.g(); }
這無法編譯錯誤:
error: cannot call member function 'int S::f()' without object
嘗試this-> f()也不起作用,因為這可能不會在該上下文中使用.
有沒有辦法使這項工作,仍然使用預設引數?
當然,它可以通過不使用預設引數來解決:
int g(int arg) { return arg; } int g() { return g(f()); }
然而,考慮到在“真實程式碼”中,在arg之前有更多的引數,以及這個模式之後的幾個函式,這是很詳細的. (如果一個函式中有多個預設引數,那麼更醜陋).
NB.最初ofollow,noindex" target="_blank">This question 看起來相似,但實際上他正在問如何形成一個關閉,這是一個不同的問題(而且連結的解決方案不適用於我的情況).
如果靜態的話,你只能使用這些成員.從C11草案(n3299),§8.3.6/ 9:
Similarly, a non-static member shall not be used in a default argument, even if it is not evaluated, unless it appears as theid-expression of a class member access expression (5.2.5) or unless it is
used to form a pointer to member (5.3.1).
例如這樣做:
struct S { static int f() { return 1; } int g(int arg = f()) { return arg; } }; int main() { S s; return s.g(); }
這也有效(我認為這是第一個表達方式):
struct S { int f() { return 42; } int g(int arg); }; static S global; int S::g(int arg = global.f()) { return arg; } int main() { S s; return s.g(); }
對此,確實是不允許的(§8.3.6/ 8):
The keywordthis
shall not be used in a default argument of a member function.
cppreference.com上的default arguments 頁有很多關於子筆的詳細資訊 – 它可以變得相當複雜.
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/36053305/is-it-possible-to-use-member-function-call-as-default-argument