虚拟运算符<<和模板 [英] Virtual operator << and templates

查看:120
本文介绍了虚拟运算符<<和模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现一种虚拟运算符<<它让我发送一个IBase类对象到cout,以便它调用Derived类'operator<<。这是可能吗?

I'm trying to implement a sort of virtual operator << that lets me send a IBase class object to cout so that it calls the Derived class' operator <<. Is this possible?

class IBase
{
public:
    IBase() {};
    virtual ~IBase() {};
};

template <typename T>
class Derived
    : public IBase
{
public:
    Derived(T data);
    template <typename U>
    friend std::ostream& operator<<(std::ostream& os, const Derived<U>& dt);
private:
    T data_;
};

template <typename T>
Derived<T>::Derived(T data)
    : IBase(),
      data_(data)
{
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const Derived<T>& dt)
{
    os << dt.data_;
    return os;
}

int _tmain(int argc, _TCHAR* argv[])
{
    IBase* base = new Derived<int>(5);

    std::cout << *base;
}


推荐答案

真正的,借助于简单的模板装配(此外,不阻止去虚拟化)。

You can make it virtual for real with a help of simple template rig (which, in addition, does not prevent de-virtualization).

struct X {
    virtual std::ostream& repr(std::ostream& out) const;
}

template <class X>
std::enable_if_t<
    std::is_same<
        std::void_t<
            decltype(std::declval<X>().repr(std::declval<std::ostream>()))>,
            void>::value,
    std::ostream&>
operator<<(X const& x)
{
    return x.repr(out);
}

这篇关于虚拟运算符&lt;&lt;和模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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