【问题标题】:can I specialize operator<<?我可以专门操作运算符<<吗?
【发布时间】:2010-07-19 20:56:03
【问题描述】:

我想专门化操作符

template<>

std::ostream& operator<< < my_type >( std::ostream& strm, my_type obj);

【问题讨论】:

    标签: c++ templates operator-overloading


    【解决方案1】:

    要专门化一个模板,首先你必须声明一个模板。

    如果是免费的operator&lt;&lt;,则不需要模板;你可以为你的my_type 类重载它:

    std::ostream& operator<<( std::ostream& strm, my_type obj );
    

    如果您的对象大小不一,您可能需要考虑通过 const 引用传递,这样您就不会在每次流式传输时都复制它:

    std::ostream& operator<<( std::ostream& strm, const my_type& obj );
    

    (从技术上讲,您可以明确专门化 operator&lt;&lt;,但我认为这不是您想要或需要的。为了能够使用具有通常

    例如

    // template op <<
    template< class T >
    std::ostream& operator<<( std::ostream&, const MyTemplClass<T>& );
    
    // specialization of above
    template<>
    std::ostream& operator<< <int>( std::ostream&, const MyTemplClass<int>& );
    

    )

    【讨论】:

    • 查尔斯请阅读我为 GMan 的回答写的评论
    • @Davit Siradeghyan:如果你有一个模板可以包罗所有 all 类型(不用说这几乎总是一个坏主意),那么你可以专门化它但是为您的特定类型重载它仍然更简单。重载解析将选择非模板函数的精确匹配而不是函数模板。
    • 我和 Charles 在一起,拥有一个完全通用的插入运算符似乎真的很危险。
    【解决方案2】:

    为什么不只是过载?

    // no template <>
    std::ostream& operator<<( std::ostream& strm, my_type obj);
    

    只有在存在模板时才能进行专业化进行专业化。

    您的参数可能应该是const my_type&amp;,以避免不必要的复制。

    【讨论】:

    • 是的,我知道重载,我需要为一组类型重载运算符
    • @Davit:您在他的问题中发布更大的图片而不是“想象”怎么样? :) 我们获得的信息越多,答案就越好。 (换句话说:发布问题,而不是步骤。)
    • 这是我的代码模板 std::ostream& operator
    猜你喜欢
    • 2015-06-04
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2019-05-15
    • 2017-10-23
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多