无法访问模板类中的好友功能

时间:2018-11-23 17:46:52

标签: c++ friend ostream

Pairwise类代表具有key:value的一对。我制作了一对模板,尝试在类中输入键和值并打印出来时遇到错误。

给出我的主意:

#include "file_name.h"

int main (){
    Pairwise<string, string> example = {{"key", "value"}};
    cout << example << endl;
 }

还有我的头文件:

#pragma once

#include<iostream>
using std::ostream; using std::cout; using std::endl;
#include<string>
using std::string;
#include<utility>
using std::pair;
#include<sstream>
using std::ostringstream;

template<typename K, typename V>
struct Pairwise{
    K first;
    V second;
    Pairwise() = default;
    Pairwise(K, V);
    //print out as a string in main
    friend ostream& operator<<(ostream &out, const Pairwise &n) {
        ostream oss;
        string s;
        oss << n.first + ":" + n.second; //possible error?
        s = oss.str();
        out << s; 
        return out;
    }
};

运行main后,我的预期输出为:

key:value

但是,我遇到了错误:

h:28:11: error: 'std::basic_ostream<_CharT, _Traits> is protected within..."

3 个答案:

答案 0 :(得分:1)

在编写时,您将运算符定义为成员函数,这很可能不是故意的。像...一样分割

template<typename K, typename V>
struct Pairwise{
    K first;
    V second;
    Pairwise() = default;
    Pairwise(K, V);
    //print out as a string in main
    friend ostream& operator<<(ostream &out, const Pairwise &n);
};

template<typename K, typename V>
ostream& operator<<(ostream &out, const Pairwise<K,V> &n) {
    ...
    return out;
}

它应该可以工作。

BTW:请注意,在struct中,默认情况下,所有成员都是公开的;因此即使没有friend声明,您也可以访问它们。

答案 1 :(得分:1)

  

h:25:59:朋友声明删除了非模板函数。

您缺少将函数声明为采用Pairwise<K, V>的模板:

header.h:

#ifndef HEADER_H_INCLUDED  /* or pragma once */
#define HEADER_H_INCLUDED  /* if you like it */

#include <iostream>  // or <ostream>

template<typename K, typename V>
class Pairwise {  // made it a class so that the
    K first;      // friend actually makes sense.
    V second;

public:
    Pairwise() = default;

    Pairwise(K first, V second)
    : first{ first }, second{ second }
    {}

    template<typename K, typename V>
    friend std::ostream& operator<<(std::ostream &out, Pairwise<K, V> const &p)
    {
        return out << p.first << ": " << p.second;
    }
};

#endif /* HEADER_H_INCLUDED */

源文件:

#include <iostream>  // the user can't know a random header includes it
#include <string>

#include "header.h"

int main()
{
    Pairwise<std::string, std::string> p{ "foo", "bar" };
    std::cout << p << '\n';
}

旁注:您也可以使用

{
    using Stringpair = Pairwise<std::string, std::string>;
    // ...
    Stringpair sp{ "foo", "bar" };
}

如果您需要更多的时间。

您将其他错误归因于将std::ostringstream中的std::ostreamoperator<<()混淆。

答案 2 :(得分:0)

在c ++中,更少通常更多...

with open("lower.lst", "r") as f:
   o = [word for word in f if (len(word) >= 4 and len(word) <= 8)]

with open("outfile.lst", "w") as f:
   f.write(o)

https://godbolt.org/z/ZUlLTu

相关问题