我有一个界面可以归结为
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/