首页 文章

ostream专业模板类的朋友功能

提问于
浏览
1
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版本中的专用模板测试类 . 我试图重载流运算符<< function . 但它显示错误信息;

C2027:使用未定义类型'std :: basic_ofstream <_Elem,_Traits>'

此外,相同的方法适用于普通函数(不是流运算符<<但我所做的函数)无论如何我们运算符<< ofstream of function in a special template class?

2 回答

  • 0

    你需要包括

    #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;
    }
    

    请注意,在头文件中使用namespace std'并不是't a good idea to have ',这就是我从示例中删除它的原因 . (当它们包含您的标头时,它可能会导致头文件的用户发生冲突)

  • 1

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

    • 你应该 #include <fstream> 并且不要忘记 using namespace std .

    • operator << 不应该是模板,它应该是一个重载函数 .

    • os << t.y 为我混淆了编译器(g 4.4.3:"warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:") . 您打算明显将int推送到流中,但编译器注意到 int 可以通过构造函数转换为 test<int> ,因此它不知道您是否要推送 inttest<int> . 这是我知道的愚蠢,可以通过构造函数 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() {
    }
    

相关问题