0

for_each最終的な目標は次のとおりですoperator<<。そのまま使えることに気づきましたostream_iteratorが、それなしで可能かどうかを確認したいと思います。

私がやりたいことのアイデアを得ることができるように、いくつかのサンプルコード:

#include <algorithm>
#include <iostream>
#include <functional>
#include <vector>

using std::bind;
using std::ref;
using std::placeholders::_1;
using std::for_each;
using std::ostream;
using std::cout;
using std::endl;
using std::vector;

class C {
    private:
        int x;
    public:
        C() : x(0) { }
        C(int x) : x(x) { }

    friend ostream& operator<<(ostream& out, const C& c);
};

ostream& operator<<(ostream& out, const C& c) {
    return out << c.x << endl;
}

int main() {
    vector<C> v;
    v.push_back(C(1));
    v.push_back(C());

    for_each(v.begin(), v.end(), bind(&ostream::operator<<, ref(cout), _1));

    return 0;
}

私が失敗したこと(上記):

bind(static_cast<ostream& (ostream::*)(ostream&, const C&)>(&ostream::operator<<), ref(cout), _1)

4

3 に答える 3

3

次のように、ラムダを使用できます。

for_each(v.begin(), v.end(), [](C const& c){ cout << c; });

個人for_each的には、シーケンス内のすべての要素にアクセスすることを意図している場合に使用することを好みます。

于 2013-02-14T20:12:06.107 に答える
3

間違ったoperator<<;を指定しています。あなたは指定しましostream::operator<<たが、あなたoperator<<は無料::operator<<です。

これは現在のプログラムで機能します。

for_each(v.begin(), v.end(), bind(&::operator<<, ref(cout), _1));

ただし、 free をさらに追加すると、どちらが意図されているかを判断できないためoperator<<、再び失敗します。その場合、明示的な特殊化を通じて指定する必要があります。bindoperator<<

for_each(v.begin(), v.end(), bind<ostream&(*)(ostream&, const C&)>(&::operator<<, ref(cout), _1));

同様に、 を使用できますstatic_cast<ostream&(*)(ostream&, const C&)>(&::operator<<)

問題は、<<instd::cout << cが自由演算子またはメンバー演算子のいずれかである可能性があり、どちらが先験的にかを知る方法がないことです。 ostream_iteratorコンパイラが式の評価方法を決定できるようにするコードを生成することによって機能します。同様に、ループにラムダまたは範囲のみを使用する場合。

于 2013-02-14T20:18:10.837 に答える
1

ここに問題はありますか?

for (auto c :v) cout<<c;

またはここ:

for (const auto& c :v) cout<<c;

またはここ:

for (C const& c :v) cout<<c;
于 2013-02-15T11:08:34.330 に答える