【问题标题】:C++ partial template specialization of stream operator流运算符的 C++ 部分模板特化
【发布时间】:2011-10-22 14:54:36
【问题描述】:

我有一个 Matrix 类,它带有一个与 operator> >),我现在想部分地专门化该友元函数以使其工作方式不同。在类定义中,我首先拥有

template <typename U>
friend std::ostream& operator<<(std::ostream& output, const Matrix<U>& other);

我尝试添加

friend std::ostream& operator<<(std::ostream& output, const Matrix<Matrix<char> >& other);

但这给了我来自编译器的多个声明错误。 我似乎无法弄清楚如何做到这一点。

【问题讨论】:

    标签: c++ template-specialization ostream friend-function


    【解决方案1】:

    There's no such thing as a partial specialization of a function template.

    您需要重载,而不是专业化。这应该可以干净地编译、链接和运行(对我来说是这样):

    #include <iostream>
    
    template <typename T>
    class Matrix {
      public:
        template <typename U> friend std::ostream& 
            operator<<(std::ostream& output, const Matrix<U>& other);
        friend std::ostream& 
            operator<<(std::ostream& output, const Matrix<Matrix<char> >& other);    
    };
    
    
    template <typename U>
    std::ostream& 
    operator<<(std::ostream& output, const Matrix<U>& other)
    {
        output << "generic\n";
        return output;
    }
    
    std::ostream& 
    operator<<(std::ostream& output, const Matrix<Matrix<char> >& other)
    {
        output << "overloaded\n";
        return output;
    }
    
    int main ()
    {
        Matrix<int> a;
        std::cout << a;
    
        Matrix<Matrix<char> > b;
        std::cout << b;
    }
    

    如果您从中得到编译器错误,则您可能有一个错误的编译器。

    【讨论】:

    • 如果我使用您的代码,当我尝试将矩阵实例与
    • 将代码更新为完整的可链接可运行程序。在 g++-4.4.5 和 g++-4.6.1 下工作。如果您将第二个 &lt;&lt; 函数的定义放在头文件中,您可以获得多个定义。不。这不是模板。
    • 您在这里的最后一条评论是我需要做出的关键改变。谢谢
    【解决方案2】:

    尝试明确地编写专业化:

    template <>
    friend std::ostream& operator<< <Matrix<char> >(std::ostream& output,
                                           const Matrix<Matrix<char> >& other);
    

    【讨论】:

    • 专业化将是 > 而不是
    • @CodeButcher 但在原始版本中,参数是 Matrix
    • @selalerer 如果我说我想创建一个这样的类的实例可能更清楚:Matrix>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    相关资源
    最近更新 更多