This project is read-only.

Generate a custom range

Jul 25, 2013 at 11:34 PM

I would like to generate a custom range using cpplinq. I see the following example in the documentation:
auto x = -1;
auto result = generate ([&]() { return (++x < 3) ?   to_opt (x) : to_opt<int> ();})
I want to do the same thing except with a range of <iovec> rather than <int>. The above sample code does not compile with the latest cpplinq header, but I am hoping that it is simply a matter of updating the syntax of the example to make it work.

Jul 26, 2013 at 12:41 PM
Could just be me, but this looks like an over-zealous use of the keyword: auto.
int x = -1;
auto result = generate([&]() {
  return (++x < 3) ? to_opt<int>(x) : to_opt<int>();
Also, not sure what to_opt<int>() does, per se. Or generate for that matter. Also noticed some obvious syntax issues.


Michael Powell
Jul 26, 2013 at 8:28 PM
Edited Jul 26, 2013 at 8:30 PM
The sample do compile for me when I try it using VS2013. OFC that doesn't necessarily mean it's correct but AFAIK auto x = -1 should result x being an int and thus the code equivalent. Which compiler did you use?

Regarding generate. Generate continues to call the generator predicate for as long as it returns an opt<> that holds a value. to_opt<int> () returns an opt<> that has no value thus terminating the generator.

So in the sample.
  1. x becomes 1. Return to_opt (1)
  2. x becomes 2. Return to_opt (2)
  3. x becomes 3. Return to_opt<int> ()
  4. Generator is terminated
The reason to_opt requires an int template parameter is because it can't infer it. I have been thinking of adding some template magic to support it but it's not sure it will be able to support the ternary operator anyway.

In order to generate a range of iovec you would do something similar to this:
auto result = generate ([&]() { 
    return are_we_done () 
        ?   to_opt (create_an_instance_of_iovec()) 
        :    to_opt<iovec> ();
Hope this helps
Jul 29, 2013 at 5:58 PM
Thank you for the thorough response. My primary question is where 'generate' and 'to_opt' are declared, as neither string appears in the latest cpplinq.hpp that I downloaded. I also cannot seem to find them in the STL.
Jul 29, 2013 at 6:10 PM
My apologies -- I must have had an old header. The new header contains both. Thanks!
Jul 29, 2013 at 6:15 PM

FYI opt<> is an optional value. It can be either "null" or has a value. The main benefit of opt over a pointer is that it has value semantics not pointer semantics (ie you don't need to delete the value).

It's very much like boost::optional. The reason for not using boost::optional is that I don't want to force the users of cpplinq to take a dependency on boost for something as small as opt.