允许派生类的流操作符

时间:2013-07-12 08:49:15

标签: c++ oop c++11

我有一个归结为

的界面
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";时,编译器会抱怨virtual void derived::write(const string&) is protected within this contextthis context是我的朋友功能)。

有没有办法实现这一点而不必为每个派生类冗余地编写流操作符?

1 个答案:

答案 0 :(得分:0)

为什么不简单地将您的运营商定义为:

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

并将您的对象传递为std::shared_ptr<interface>

相关问题