簡體   English   中英

不理解的模板和可訪問性行為

[英]Non understood template and accessibility behavior

無論如何, A::Stuffprotected的,那么為什么繼承自A並強制其成員的可訪問性protected導致錯誤?

class A {
   protected:
    template <typename T>
    static void Stuff() {
        T::template Stuff<T>();
    }
};

class B : protected A {
   public:
    void something() { A::Stuff<B>(); }

    // I have these two, inelegant workarounds:
    // using A::Stuff;    // KO: This is wrong, it changes the accessibility of Stuff.
    // class B : public A // KO: Accessibility changed.
    // friend A;          // OK: This seems fine.
};

int main() {
    B b;
    b.something();
}

代碼位於: https://godbolt.org/z/r1Ya3rzsK

假設上面定義的類AB clang 和 gcc 會給你這樣的東西:

'Stuff' is a protected member of 'A'
        T::template Stuff<T>();

我在評論中給出了一個解決方法,只要成員的可訪問性沒有改變,歡迎更多。

問題是A::Stuff<B>()將調用T::Stuff<T>()T=B aka B::Stuff<B>() B 沒有Stuff function,因此它會嘗試回退到無效的A::Stuff ,因為您保護了 inheritance。 (順便說一句,如果它是有效的,因為 inheritance 是公開的,這將導致無限遞歸)。

我認為你不想在這里無限遞歸。 如果您希望Stuff<B>有效,請將Stuff function 添加到 B。

#include <iostream>
class A {
   protected:
    template <typename T>
    static void Stuff() {
        std::cout<<"called A\n";
        T::template Stuff<T>();
    }
};

class B : protected A {
   public:
    void something() { A::Stuff<B>(); }

    template <typename T>
    static void Stuff() {
        std::cout<<"called B\n";
        //...
    }
    // I have these two, inelegant workarounds:
    // using A::Stuff;    // KO: This is wrong, it changes the visibility of Stuff.
    // class B : public A // KO: Visibility changed.
    // friend A;          // OK: This seems fine.
};

int main() {
    B b;
    b.something();
}

暫無
暫無

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

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