【问题标题】:ostream friend function of specialized template classostream 专用模板类的友元函数
【发布时间】:2012-01-23 15:23:39
【问题描述】:
template <> 
class test<int> {
    int y; 
public:     
    test(int k) : y(k) {}     
    friend ofstream& operator<< <test<int>> (ofstream& os, const test<int>& t); 
};  
template<> 
ofstream& operator<< <test<int> > (ofstream& os, const test<int>& t) 
{
    os << t.y;
    return os;
}  

上面的代码是 int 版本的专用测试模板类。我正在尝试重载 ofstream 运算符

C2027:使用未定义类型 'std::basic_ofstream<_elem>'

此外,同样的方法适用于普通函数(不是 ofstream 运算符

【问题讨论】:

  • 您是否包含&lt;fstream&gt; 或仅包含&lt;ios_fwd&gt;

标签: c++ templates friend


【解决方案1】:

你需要包含

 #include <iostream>

函数模板实例化时。也许你只包括

 #include <iosfwd>

此外,您不应将(静态)朋友定义为模板:https://ideone.com/1HRlZ

#include <iostream>

template <typename> class test;

template <> 
class test<int> {
    int y; 
public:     
    test(int k) : y(k) {}     
    friend std::ostream& operator<<(std::ostream& os, const test& t); 
};  

std::ostream& operator<< (std::ostream& os, const test<int>& t) 
{
    return os << t.y;
}  

int main()
{
    test<int> a(42);
    std::cout << a << std::endl;
}

请注意,在头文件中包含“using namespace std”并不是一个好主意,这就是我从示例中删除它的原因。 (当他们包含您的标头时,可能会导致您的标头文件的用户发生冲突

【讨论】:

  • 修复了完成测试的 ostream 运算符的另一个问题:ideone.com/1HRlZ
  • 我实际上包含了两个头文件,但错误并没有消失
【解决方案2】:

这里有很多有趣的问题。首先是明显的家务

  • 你应该#include &lt;fstream&gt;,不要忘记using namespace std
  • operator &lt;&lt; 不应该是模板,而应该是重载函数。
  • os &lt;&lt; t.y 混淆了我的编译器(g++ 4.4.3:“警告:ISO C++ 说这些是模棱两可的,即使第一个的最差转换比第二个的最差转换更好:” )。您显然打算将 int 推送到流中,但编译器注意到 int 可以通过您的构造函数转换为 test&lt;int&gt;,因此它不知道您是要推送 int 还是 @ 987654328@。我知道这很愚蠢,可以通过构造构造函数explicit来解决。

    #include <fstream>
    using namespace std;
    template <typename T>
    class test;
    
    template <>
    class test<int> {
        int y;
    public:
        explicit test(int k) : y(k) {}
        // friend ofstream& operator<<   < test<int> > (ofstream& os, const test<int>& t); 
        friend ofstream& operator<< (ofstream& os, const test<int>& t);
    };
    // template<> 
    // ofstream& operator<< <test<int> > (ofstream& os, const test<int>& t) 
    ofstream& operator<<  (ofstream& os, const test<int>& t)
    {
        os << t.y;
        return os;
    }
    int main() {
    }
    

【讨论】:

    猜你喜欢
    • 2013-08-19
    • 1970-01-01
    • 2010-12-19
    • 2011-07-15
    • 1970-01-01
    • 2016-10-19
    • 2013-09-18
    • 1970-01-01
    相关资源
    最近更新 更多