Ian
Ian

Reputation: 450

Can regex_iterators be used on a custom string type?

I have only found examples of regex_iterators being intialised as

regex_iterator::<string::iterator>

If I have a class which contains a sequence of characters, such as:

class fooString {
private:
  deque<bar> data;

  // ... other functionality ...
}

Where bar is a class or struct that is compatible with std::to_string

How would I make fooString and bar compatible with regex so that I could call

fooString myFoo = ...
regex e( /* some regex notation */);
regex_iterator::<fooString::iterator> regIt(myFoo.begin(), myFoo.end(), e);

...and be able to iterate over it as I would with a string?


I tried the following experiement:

    std::deque<int> testDeque { 4, 5, 5, 5, 6, 7 };
    std::regex e("5{1,3}");
    std::regex_iterator<std::deque<int>::iterator> 
    regIt(testDeque.begin(), testDeque.end(), e);

And get the compilation error

1>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\regex(2271): error C2027: use of undefined type 'std::regex_traits<_Elem>'
with  
[  
   _Elem=int  
]

So I don't think the bidirectional iterator is enough since deque complies with that, I think the 'bar' object needs to be compatible. But I'm really not sure.

Upvotes: 1

Views: 130

Answers (1)

AndyG
AndyG

Reputation: 41092

fooString must satisfy the requirements of a bidirectional iterator. [bidirectional.iterators] cppreference's documentation is extremely close to the standard wording, so you'd be okay following it.

I will add the relevant portions here:

  • The iterator, r, must satisfy both operations --r and r++
    • these operations return a reference to an iterator of the same type
  • *r must return a reference to the type the iterator is iterating over.
    • a reference type according to what cppreference lists for iterator_traits

If your BidirectionalIterator::value_type is not a standard character type (anything you could make a std::basic_string with, e.g., char), you'll also need to specialize regex_traits, although this is going down quite the rabbit hole.

Upvotes: 2

Related Questions