允许派生类上的流操作符 [英] Allow stream operator on derived classes

查看:105
本文介绍了允许派生类上的流操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口,可以归结为

I have an interface that boils down to

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> 。我希望我可以重载<< 运算符,但只有我的界面的派生的智能指针。我试过这个:

In my application, these objects are passed around as smart pointers, i.e. std::shared_ptr<derived>. I hoped I could overload the << operator, but only for smart pointer of derivatives of my interface. I tried this:

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& sp; sp < test; ,编译器指出 virtual void derived :: write(const string&)在此上下文中被保护这个上下文是我的朋友函数)。

But when I try std::shared_ptr<derived> sp; sp << "test";, the compiler complains that virtual void derived::write(const string&) is protected within this context (this context is my friend function).

有没有办法实现这个没有冗余地为每个派生类写一个流运算符?

Is there a way to achieve this without redundantly writing a stream operator for every derived class?

推荐答案

为什么不简单地将您的运算符定义为:

Why not simply define your operator as:

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

并传递 std :: shared_ptr< interface>

这篇关于允许派生类上的流操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆