我正在设计一种istream_iterator
(称为my_istream_iterator
)旨在从输入流中提取单词的方法。处理从迭代器中提取的单词的方式与流中单词的分隔方式无关,但单词本身可能遵循多种格式中的一种。为了适应这一点,我希望用户能够在创建my_istream_iterator
使用输入流时指定策略类,而无需用户在迭代器的模板参数列表中指定策略类的类型。例如,如果我想以行优先顺序输出 CSV 文件中的条目,我希望能够执行以下操作:
std::ifstream is("words.csv");
// Assume that the_policy_class is used to read a special kind
// of CSV file that deviates from the standard specification.
// I don't want to have to specify the type of the policy class
// used by the iterator; how would I be able to do this? (The
// value_type of `mystream_iterator` is always char*).
my_istream_iterator begin = csv_begin<the_policy_class>(
is, the_policy_class('\t', '\n', 1));
// Default constructor for end-of-stream iterator.
my_istream_iterator end;
std::ostream_iterator<char*> out(std::cout, ", ");
// Print the words, delimited by commas, to stdout.
std::copy(begin, end, out);
mystream_iterator
即使迭代器在内部使用策略类,如何在创建时保留指定策略类类型的用户表单?这可能吗?
谢谢你的帮助!
如果有帮助,my_istream_iterator
类的定义可能看起来像这样:
template <typename Character, typename CharTraits = std::char_traits<Character>,
typename Distance = std::ptrdiff_t>
class basic_my_istream_iterator : public std::iterator<std::input_iterator_tag,
const Character*, Distance>
{
/* ... */
};
typedef basic_my_istream_iterator<char> my_istream_iterator;
typedef basic_my_istream_iterator<wchar_t> my_wistream_iterator;