c++ - 允许在派生类上使用流运算符

标签 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> .我希望我可以重载 <<运算符,但仅适用于我的接口(interface)的衍生物的智能指针。我试过这个:

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 context (this context 是我的友元函数)。

有没有办法在不为每个派生类冗余编写流运算符的情况下实现这一目标?

最佳答案

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

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

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

关于c++ - 允许在派生类上使用流运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17610986/

相关文章:

python - 如何从父调用子构造函数?

java - 为什么标准类有时具有看似不相关的方法?

c++ - 双参数构造函数的用户定义文字

c++ - 将 1d 矩阵模式设置为等于 2d 矩阵

javascript - 在javascript中创建对象时动态控制参数

c++ - 如何在 C++ Windows 游戏中播放声音?

c++ - 如何根据 C++11 中的特定条件从 vector 中删除元素

c++ - nullptr_t驻留在哪里?

c++ - 通过C++中的引用声明传递

c++ - Boost.Test 崩溃并出现 ***Exception : Other on MSVC