3

私は経験していてboost::variant、どうすればフォローを機能させることができるのか疑問に思っていましたか?

typedef boost::variant<int,std::string> myval;
int main()
{

std::vector<myval> vec;

std::ifstream fin("temp.txt");

//How following can be achieved ?
std::copy(std::istream_iterator<myval>(fin), //Can this be from std::cin too ?
          std::istream_iterator<myval>(),
          std::back_inserter(vec));   
}

クラス データ メンバーの場合、>>演算子をオーバーロードするオプションがありますが、これを行う方法はmyval?

4

2 に答える 2

3

他の型operator>>と同じようにオーバーロードできます。variantただし、どの型をストリームから読み取って に格納するかを決定するロジックを実装するのは開発者次第ですvariant。以下は、その方法の完全な例です。

#include "boost/variant.hpp"
#include <iostream>
#include <cctype>
#include <vector>
#include <string>

typedef boost::variant<int, std::string> myval;

namespace boost { // must be in boost namespace to be found by ADL
std::istream& operator>>(std::istream& in, myval& v)
{
    in >> std::ws;      // throw away leading whitespace
    int c = in.peek();
    if (c == EOF) return in;  // nothing to read, done

    // read int if there's a minus or a digit
    // TODO: handle the case where minus is not followed by a digit
    // because that's supposed to be an error or read as a string
    if (std::isdigit(static_cast<unsigned char>(c)) || c == '-') {
        int i;
        in >> i;
        v = i;
    } else {
        std::string s;
        in >> s;
        v = s;
    }
    return in;
}
} // namespace boost

// visitor to query the type of value
struct visitor : boost::static_visitor<std::string> {
    std::string operator()(const std::string&) const
    {
        return "string";
    }
    std::string operator()(int) const
    {
        return "int";
    }
};

int main()
{
    std::vector<myval> vec;
    std::copy(
        std::istream_iterator<myval>(std::cin),
        std::istream_iterator<myval>(),
        std::back_inserter(vec));

    std::cout << "Types read:\n";
    for (const auto& v : vec) {
        std::string s = boost::apply_visitor(visitor(), v);
        std::cout << s << '\n';
    }
}

入力例:1 2 3 hello 4 world

出力:

Types read:
int
int
int
string
int
string
于 2013-08-02T08:20:31.667 に答える
0

myvalは単なるタイプです。型に基づいて演算子をオーバーロードします。

std::istream &operator >>(std::istream &stream, myval &val)
{
    //Put stuff here.
}

そこに何を入れるかについては、それは完全にあなた次第であり、ストリームに何を期待または要求するかはあなた次第です。

于 2013-08-02T07:56:01.000 に答える