簡體   English   中英

在派生類上允許流運算符

[英]Allow stream operator on derived classes

我有一個歸結為

class interface
{
    protected:
        virtual void write(std::string const &) = 0;
};

和派生類

class derived : public interface
{
    protected:
        void write(std::string const & buf) 
        { 
            std::cout << buf << std::endl; 
        }
};

在我的應用程序中,這些對象作為智能指針傳遞,即std::shared_ptr<derived> 我希望我可以重載<<運算符,但僅用於接口派生的智能指針。 我嘗試了這個:

class interface
{
    /* ... */
    private:
        template <typename Derived> friend typename std::enable_if<
            std::is_base_of<interface, Derived>::value,
            std::shared_ptr<Derived>
        >::type & operator<<(std::shared_ptr<Derived> & lhs,
                std::string const & rhs)
        {
            lhs->write(rhs);
            return lhs;
        }
};

但是當我嘗試std::shared_ptr<derived> sp; sp << "test"; std::shared_ptr<derived> sp; sp << "test"; ,編譯器抱怨virtual void derived::write(const string&) is protected within this contextthis context是我的朋友函數)。

有沒有一種方法可以在不為每個派生類冗余編寫流運算符的情況下實現這一目標?

為什么不簡單地將您的運算符定義為:

friend std::shared_ptr<interface> &operator<<(std::shared_ptr<interface> & lhs, std::string const & rhs);

並將您的對象作為std::shared_ptr<interface>傳遞?

暫無
暫無

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

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