簡體   English   中英

在成員 function 中使用聲明作為繼承的成員字段

[英]using declaration inside a member function for an inherited member field

在 function 中,可以使用 using 聲明在當前 scope 中導入名稱,例如

namespace A {
   int y;
}

void f() { using A::y; }

using 聲明可用於 class 定義,以更改繼承成員的可訪問性,但顯式引入從模板 class 繼承的成員也很有用

template <bool activate>
struct A {
   int x;
};

template <bool activate>
struct B : public A<activate> {
   using A<activate>::x;
};

這特別有用,因為它避免了通過this->xA<activate>::x訪問x的需要。 這只能在定義主體內部使用,但不能在成員 function 內部使用。

template <bool activate>
struct A {
   int x;
};

template <bool activate>
struct B : public A<activate> {
   int f() const noexcept {
       // This gives: "error: using-declaration for member at non-class scope"
       // using A<activate>::x;
       return x;
   }
};

這種語言限制是否有理由,即using A<activate>::x只能放在 class 的定義中?

C++ 的 Design & Evolution 中沒有關於這個主題的直接陳述,很難可靠地推斷出這樣的事情的意圖。 也就是說,直到最近,該標准將using-declaration描述為引入聲明作為命名聲明的同義詞。 在這種情況下,成員聲明屬於塊 scope 會有點奇怪。現在它們被認為是重定向,在名稱查找期間被它們的引用對象替換,這與這種概念用法更一致。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM