How should I replace vector::const_iterator in an API? The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceWhat is a “span” and when should I use one?Singleton: How should it be usedHow to find out if an item is present in a std::vector?How do I erase an element from std::vector<> by index?How to replace all occurrences of a character in string?How to convert vector to arrayHow to correctly implement custom iterators and const_iterators?Interface-based programming in C++ in combination with iterators. How too keep this simple?How to implement the factory method pattern in C++ correctlyHow to print out the contents of a vector?Vector, iterators and const_iterator

University's motivation for having tenure-track positions

Do working physicists consider Newtonian mechanics to be "falsified"?

Can a novice safely splice in wire to lengthen 5V charging cable?

Typeface like Times New Roman but with "tied" percent sign

What aspect of planet Earth must be changed to prevent the industrial revolution?

Would an alien lifeform be able to achieve space travel if lacking in vision?

How many people can fit inside Mordenkainen's Magnificent Mansion?

How do I add random spotting to the same face in cycles?

Sort list of array linked objects by keys and values

How to politely respond to generic emails requesting a PhD/job in my lab? Without wasting too much time

Arduino Pro Micro - switch off LEDs

Does Parliament need to approve the new Brexit delay to 31 October 2019?

How did the audience guess the pentatonic scale in Bobby McFerrin's presentation?

What do you call a plan that's an alternative plan in case your initial plan fails?

First use of “packing” as in carrying a gun

Why does the Event Horizon Telescope (EHT) not include telescopes from Africa, Asia or Australia?

Scientific Reports - Significant Figures

How do you keep chess fun when your opponent constantly beats you?

Can the DM override racial traits?

ELI5: Why do they say that Israel would have been the fourth country to land a spacecraft on the Moon and why do they call it low cost?

Mortgage adviser recommends a longer term than necessary combined with overpayments

Single author papers against my advisor's will?

Did God make two great lights or did He make the great light two?

Finding the path in a graph from A to B then back to A with a minimum of shared edges



How should I replace vector::const_iterator in an API?



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceWhat is a “span” and when should I use one?Singleton: How should it be usedHow to find out if an item is present in a std::vector?How do I erase an element from std::vector<> by index?How to replace all occurrences of a character in string?How to convert vector to arrayHow to correctly implement custom iterators and const_iterators?Interface-based programming in C++ in combination with iterators. How too keep this simple?How to implement the factory method pattern in C++ correctlyHow to print out the contents of a vector?Vector, iterators and const_iterator



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








7















I've been given the task of polishing the interface of a codec library. We're using C++17, and I can only use the standard library (i.e. no Boost). Currently, there's a Decoder class that looks roughly like this:



class Decoder : public Codec 

public:

struct Result
vector<uint8_t>::const_iterator new_buffer_begin;
optional<Metadata> metadata;
optional<Packet> packet;
;

Result decode(vector<uint8_t>::const_iterator buffer_begin,
vector<uint8_t>::const_iterator buffer_end);

private:
// irrelevant details
;


The caller instantiates a Decoder, then feeds a stream of data to the decoder by



  1. Reading a chunk of data from a file (but there could be other sources in the future), and appending it to a vector<uint8_t>.


  2. Calling the decode function, passing the iterators for their vector.


  3. If the returned Result's new_buffer_begin is identical to the buffer_begin that was passed to decode, that means there wasn't enough data in the buffer to decode anything, and the caller should go back to step 1. Otherwise, the caller consumes the Metadata or Packet object that was decoded, and goes back to step 2, using new_buffer_begin for the next pass.


The things I dislike about this interface and need help improving:



  • Using vector<uint8_t>::const_iterator seems overly specific. Is there a more generic approach that doesn't force the caller to use vector? I was considering just using C-style interface; a uint8_t * and a length. Is there a C++ alternative that's fairly generic?


  • If there was enough data to decode something, only metadata or packet will have a value. I think std::variant or 2 callbacks (one for each type) would make this code more self-documenting. I'm not sure which is more idiomatic though. What are the pros and cons of each, and is there an even better approach?










share|improve this question






















  • Is there a C++ alternative that's fairly generic? Templates.

    – tkausl
    1 hour ago











  • typedef vector<uint8_t>::const_iterator it_t; or using it_t= vector<uint8_t>::const_iterator; will make it cleaner.

    – Mirko
    1 hour ago






  • 1





    I like the callback approach, passing a consumer object with a callback for each kind of result produced. When the method return you give the guaranty that at most one callback has been called. But you could also have an async variant. The API could evolve by adding more callback to the consumer. std::variant is also good but may require the user to check which one is available (doesn't really change from two optionals).

    – semako
    39 mins ago

















7















I've been given the task of polishing the interface of a codec library. We're using C++17, and I can only use the standard library (i.e. no Boost). Currently, there's a Decoder class that looks roughly like this:



class Decoder : public Codec 

public:

struct Result
vector<uint8_t>::const_iterator new_buffer_begin;
optional<Metadata> metadata;
optional<Packet> packet;
;

Result decode(vector<uint8_t>::const_iterator buffer_begin,
vector<uint8_t>::const_iterator buffer_end);

private:
// irrelevant details
;


The caller instantiates a Decoder, then feeds a stream of data to the decoder by



  1. Reading a chunk of data from a file (but there could be other sources in the future), and appending it to a vector<uint8_t>.


  2. Calling the decode function, passing the iterators for their vector.


  3. If the returned Result's new_buffer_begin is identical to the buffer_begin that was passed to decode, that means there wasn't enough data in the buffer to decode anything, and the caller should go back to step 1. Otherwise, the caller consumes the Metadata or Packet object that was decoded, and goes back to step 2, using new_buffer_begin for the next pass.


The things I dislike about this interface and need help improving:



  • Using vector<uint8_t>::const_iterator seems overly specific. Is there a more generic approach that doesn't force the caller to use vector? I was considering just using C-style interface; a uint8_t * and a length. Is there a C++ alternative that's fairly generic?


  • If there was enough data to decode something, only metadata or packet will have a value. I think std::variant or 2 callbacks (one for each type) would make this code more self-documenting. I'm not sure which is more idiomatic though. What are the pros and cons of each, and is there an even better approach?










share|improve this question






















  • Is there a C++ alternative that's fairly generic? Templates.

    – tkausl
    1 hour ago











  • typedef vector<uint8_t>::const_iterator it_t; or using it_t= vector<uint8_t>::const_iterator; will make it cleaner.

    – Mirko
    1 hour ago






  • 1





    I like the callback approach, passing a consumer object with a callback for each kind of result produced. When the method return you give the guaranty that at most one callback has been called. But you could also have an async variant. The API could evolve by adding more callback to the consumer. std::variant is also good but may require the user to check which one is available (doesn't really change from two optionals).

    – semako
    39 mins ago













7












7








7








I've been given the task of polishing the interface of a codec library. We're using C++17, and I can only use the standard library (i.e. no Boost). Currently, there's a Decoder class that looks roughly like this:



class Decoder : public Codec 

public:

struct Result
vector<uint8_t>::const_iterator new_buffer_begin;
optional<Metadata> metadata;
optional<Packet> packet;
;

Result decode(vector<uint8_t>::const_iterator buffer_begin,
vector<uint8_t>::const_iterator buffer_end);

private:
// irrelevant details
;


The caller instantiates a Decoder, then feeds a stream of data to the decoder by



  1. Reading a chunk of data from a file (but there could be other sources in the future), and appending it to a vector<uint8_t>.


  2. Calling the decode function, passing the iterators for their vector.


  3. If the returned Result's new_buffer_begin is identical to the buffer_begin that was passed to decode, that means there wasn't enough data in the buffer to decode anything, and the caller should go back to step 1. Otherwise, the caller consumes the Metadata or Packet object that was decoded, and goes back to step 2, using new_buffer_begin for the next pass.


The things I dislike about this interface and need help improving:



  • Using vector<uint8_t>::const_iterator seems overly specific. Is there a more generic approach that doesn't force the caller to use vector? I was considering just using C-style interface; a uint8_t * and a length. Is there a C++ alternative that's fairly generic?


  • If there was enough data to decode something, only metadata or packet will have a value. I think std::variant or 2 callbacks (one for each type) would make this code more self-documenting. I'm not sure which is more idiomatic though. What are the pros and cons of each, and is there an even better approach?










share|improve this question














I've been given the task of polishing the interface of a codec library. We're using C++17, and I can only use the standard library (i.e. no Boost). Currently, there's a Decoder class that looks roughly like this:



class Decoder : public Codec 

public:

struct Result
vector<uint8_t>::const_iterator new_buffer_begin;
optional<Metadata> metadata;
optional<Packet> packet;
;

Result decode(vector<uint8_t>::const_iterator buffer_begin,
vector<uint8_t>::const_iterator buffer_end);

private:
// irrelevant details
;


The caller instantiates a Decoder, then feeds a stream of data to the decoder by



  1. Reading a chunk of data from a file (but there could be other sources in the future), and appending it to a vector<uint8_t>.


  2. Calling the decode function, passing the iterators for their vector.


  3. If the returned Result's new_buffer_begin is identical to the buffer_begin that was passed to decode, that means there wasn't enough data in the buffer to decode anything, and the caller should go back to step 1. Otherwise, the caller consumes the Metadata or Packet object that was decoded, and goes back to step 2, using new_buffer_begin for the next pass.


The things I dislike about this interface and need help improving:



  • Using vector<uint8_t>::const_iterator seems overly specific. Is there a more generic approach that doesn't force the caller to use vector? I was considering just using C-style interface; a uint8_t * and a length. Is there a C++ alternative that's fairly generic?


  • If there was enough data to decode something, only metadata or packet will have a value. I think std::variant or 2 callbacks (one for each type) would make this code more self-documenting. I'm not sure which is more idiomatic though. What are the pros and cons of each, and is there an even better approach?







c++ c++17 binary-data idiomatic






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 1 hour ago









splicersplicer

3,86243545




3,86243545












  • Is there a C++ alternative that's fairly generic? Templates.

    – tkausl
    1 hour ago











  • typedef vector<uint8_t>::const_iterator it_t; or using it_t= vector<uint8_t>::const_iterator; will make it cleaner.

    – Mirko
    1 hour ago






  • 1





    I like the callback approach, passing a consumer object with a callback for each kind of result produced. When the method return you give the guaranty that at most one callback has been called. But you could also have an async variant. The API could evolve by adding more callback to the consumer. std::variant is also good but may require the user to check which one is available (doesn't really change from two optionals).

    – semako
    39 mins ago

















  • Is there a C++ alternative that's fairly generic? Templates.

    – tkausl
    1 hour ago











  • typedef vector<uint8_t>::const_iterator it_t; or using it_t= vector<uint8_t>::const_iterator; will make it cleaner.

    – Mirko
    1 hour ago






  • 1





    I like the callback approach, passing a consumer object with a callback for each kind of result produced. When the method return you give the guaranty that at most one callback has been called. But you could also have an async variant. The API could evolve by adding more callback to the consumer. std::variant is also good but may require the user to check which one is available (doesn't really change from two optionals).

    – semako
    39 mins ago
















Is there a C++ alternative that's fairly generic? Templates.

– tkausl
1 hour ago





Is there a C++ alternative that's fairly generic? Templates.

– tkausl
1 hour ago













typedef vector<uint8_t>::const_iterator it_t; or using it_t= vector<uint8_t>::const_iterator; will make it cleaner.

– Mirko
1 hour ago





typedef vector<uint8_t>::const_iterator it_t; or using it_t= vector<uint8_t>::const_iterator; will make it cleaner.

– Mirko
1 hour ago




1




1





I like the callback approach, passing a consumer object with a callback for each kind of result produced. When the method return you give the guaranty that at most one callback has been called. But you could also have an async variant. The API could evolve by adding more callback to the consumer. std::variant is also good but may require the user to check which one is available (doesn't really change from two optionals).

– semako
39 mins ago





I like the callback approach, passing a consumer object with a callback for each kind of result produced. When the method return you give the guaranty that at most one callback has been called. But you could also have an async variant. The API could evolve by adding more callback to the consumer. std::variant is also good but may require the user to check which one is available (doesn't really change from two optionals).

– semako
39 mins ago












3 Answers
3






active

oldest

votes


















4














In addition to @Justin's valid suggestion of spans:



  • You might also want to consider using std::byte instead of uint8_t, so:

    Result decode(std::span<const std::byte> buffer);



  • If you want to support decoding from containers other than raw memory, use arbitrary iterators (in C++17 and earlier) or possibly ranges (in C++20). The iterator version:



    template <typename InputIt>
    Result decode(InputIt start, InputIt end) /* etc. */


  • It's fishy that a Decoder inherits from a Codec rather than the other way around.


  • The question of whether callbacks are a good choice or not is something that's difficult (for me) to answer without seeing the code. But do indeed use an std::variant to express the fact you have either a Packet or Metadata; you could also "combine" both your options if instead of callbacks you use variants' std::visit.





share|improve this answer

























  • Decoder and another class, Encoder, inherit from Codec because Codec provides the majority of maintained state and a bunch of shared logic. Unfortunately, I'm not allowed to share the code; just the interface. Your suggestion of using std::visit looks promising. Thanks!

    – splicer
    12 mins ago











  • @splicer: In that case, consider either renaming Encoder or perhaps taking some functionality out into a namespace.

    – einpoklum
    11 mins ago


















3














C++20 will have std::span, which does what you want:



 Result decode(std::span<uint8_t const> buffer);


std::span<T> is semantically equivalent to a T* buffer, size_t size.




In C++17, there are some implementations of a span type which are equivalent to std::span, such as the GSL's gsl::span. See What is a "span" and when should I use one? .



If you can't use any external libraries, consider writing your own span type, else
uint8_t const* buffer_begin, uint8_t const* buffer_end can work.






share|improve this answer






























    3














    I agree that mandating vector is inappropriate, and applaud your attempts to make the interface more useful.



    If decode expects a contiguous sequence of uint8_t, the tried-and-tested (and most flexible) solution is just to take a const uint8_t* and a std::size_t (or alternatively two pointers, but pointer and length is more idiomatic).



    From C++20 you can do this with one argument of type std::span<const uint8_t>. Or going back to pointers, if you really want to use modern library tools for the sake of it, you can confuse people with std::experimental::observer_ptr.



    You may also consider making decode a template that accepts any iterator pair, and (if contiguity is needed) mandates, even if only by documentation, that the iterators reflect a contiguous sequence. But making everything a template isn't always what you want, and it isn't always useful.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55670315%2fhow-should-i-replace-vectoruint8-tconst-iterator-in-an-api%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      In addition to @Justin's valid suggestion of spans:



      • You might also want to consider using std::byte instead of uint8_t, so:

        Result decode(std::span<const std::byte> buffer);



      • If you want to support decoding from containers other than raw memory, use arbitrary iterators (in C++17 and earlier) or possibly ranges (in C++20). The iterator version:



        template <typename InputIt>
        Result decode(InputIt start, InputIt end) /* etc. */


      • It's fishy that a Decoder inherits from a Codec rather than the other way around.


      • The question of whether callbacks are a good choice or not is something that's difficult (for me) to answer without seeing the code. But do indeed use an std::variant to express the fact you have either a Packet or Metadata; you could also "combine" both your options if instead of callbacks you use variants' std::visit.





      share|improve this answer

























      • Decoder and another class, Encoder, inherit from Codec because Codec provides the majority of maintained state and a bunch of shared logic. Unfortunately, I'm not allowed to share the code; just the interface. Your suggestion of using std::visit looks promising. Thanks!

        – splicer
        12 mins ago











      • @splicer: In that case, consider either renaming Encoder or perhaps taking some functionality out into a namespace.

        – einpoklum
        11 mins ago















      4














      In addition to @Justin's valid suggestion of spans:



      • You might also want to consider using std::byte instead of uint8_t, so:

        Result decode(std::span<const std::byte> buffer);



      • If you want to support decoding from containers other than raw memory, use arbitrary iterators (in C++17 and earlier) or possibly ranges (in C++20). The iterator version:



        template <typename InputIt>
        Result decode(InputIt start, InputIt end) /* etc. */


      • It's fishy that a Decoder inherits from a Codec rather than the other way around.


      • The question of whether callbacks are a good choice or not is something that's difficult (for me) to answer without seeing the code. But do indeed use an std::variant to express the fact you have either a Packet or Metadata; you could also "combine" both your options if instead of callbacks you use variants' std::visit.





      share|improve this answer

























      • Decoder and another class, Encoder, inherit from Codec because Codec provides the majority of maintained state and a bunch of shared logic. Unfortunately, I'm not allowed to share the code; just the interface. Your suggestion of using std::visit looks promising. Thanks!

        – splicer
        12 mins ago











      • @splicer: In that case, consider either renaming Encoder or perhaps taking some functionality out into a namespace.

        – einpoklum
        11 mins ago













      4












      4








      4







      In addition to @Justin's valid suggestion of spans:



      • You might also want to consider using std::byte instead of uint8_t, so:

        Result decode(std::span<const std::byte> buffer);



      • If you want to support decoding from containers other than raw memory, use arbitrary iterators (in C++17 and earlier) or possibly ranges (in C++20). The iterator version:



        template <typename InputIt>
        Result decode(InputIt start, InputIt end) /* etc. */


      • It's fishy that a Decoder inherits from a Codec rather than the other way around.


      • The question of whether callbacks are a good choice or not is something that's difficult (for me) to answer without seeing the code. But do indeed use an std::variant to express the fact you have either a Packet or Metadata; you could also "combine" both your options if instead of callbacks you use variants' std::visit.





      share|improve this answer















      In addition to @Justin's valid suggestion of spans:



      • You might also want to consider using std::byte instead of uint8_t, so:

        Result decode(std::span<const std::byte> buffer);



      • If you want to support decoding from containers other than raw memory, use arbitrary iterators (in C++17 and earlier) or possibly ranges (in C++20). The iterator version:



        template <typename InputIt>
        Result decode(InputIt start, InputIt end) /* etc. */


      • It's fishy that a Decoder inherits from a Codec rather than the other way around.


      • The question of whether callbacks are a good choice or not is something that's difficult (for me) to answer without seeing the code. But do indeed use an std::variant to express the fact you have either a Packet or Metadata; you could also "combine" both your options if instead of callbacks you use variants' std::visit.






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 35 mins ago

























      answered 40 mins ago









      einpoklumeinpoklum

      37.3k28134263




      37.3k28134263












      • Decoder and another class, Encoder, inherit from Codec because Codec provides the majority of maintained state and a bunch of shared logic. Unfortunately, I'm not allowed to share the code; just the interface. Your suggestion of using std::visit looks promising. Thanks!

        – splicer
        12 mins ago











      • @splicer: In that case, consider either renaming Encoder or perhaps taking some functionality out into a namespace.

        – einpoklum
        11 mins ago

















      • Decoder and another class, Encoder, inherit from Codec because Codec provides the majority of maintained state and a bunch of shared logic. Unfortunately, I'm not allowed to share the code; just the interface. Your suggestion of using std::visit looks promising. Thanks!

        – splicer
        12 mins ago











      • @splicer: In that case, consider either renaming Encoder or perhaps taking some functionality out into a namespace.

        – einpoklum
        11 mins ago
















      Decoder and another class, Encoder, inherit from Codec because Codec provides the majority of maintained state and a bunch of shared logic. Unfortunately, I'm not allowed to share the code; just the interface. Your suggestion of using std::visit looks promising. Thanks!

      – splicer
      12 mins ago





      Decoder and another class, Encoder, inherit from Codec because Codec provides the majority of maintained state and a bunch of shared logic. Unfortunately, I'm not allowed to share the code; just the interface. Your suggestion of using std::visit looks promising. Thanks!

      – splicer
      12 mins ago













      @splicer: In that case, consider either renaming Encoder or perhaps taking some functionality out into a namespace.

      – einpoklum
      11 mins ago





      @splicer: In that case, consider either renaming Encoder or perhaps taking some functionality out into a namespace.

      – einpoklum
      11 mins ago













      3














      C++20 will have std::span, which does what you want:



       Result decode(std::span<uint8_t const> buffer);


      std::span<T> is semantically equivalent to a T* buffer, size_t size.




      In C++17, there are some implementations of a span type which are equivalent to std::span, such as the GSL's gsl::span. See What is a "span" and when should I use one? .



      If you can't use any external libraries, consider writing your own span type, else
      uint8_t const* buffer_begin, uint8_t const* buffer_end can work.






      share|improve this answer



























        3














        C++20 will have std::span, which does what you want:



         Result decode(std::span<uint8_t const> buffer);


        std::span<T> is semantically equivalent to a T* buffer, size_t size.




        In C++17, there are some implementations of a span type which are equivalent to std::span, such as the GSL's gsl::span. See What is a "span" and when should I use one? .



        If you can't use any external libraries, consider writing your own span type, else
        uint8_t const* buffer_begin, uint8_t const* buffer_end can work.






        share|improve this answer

























          3












          3








          3







          C++20 will have std::span, which does what you want:



           Result decode(std::span<uint8_t const> buffer);


          std::span<T> is semantically equivalent to a T* buffer, size_t size.




          In C++17, there are some implementations of a span type which are equivalent to std::span, such as the GSL's gsl::span. See What is a "span" and when should I use one? .



          If you can't use any external libraries, consider writing your own span type, else
          uint8_t const* buffer_begin, uint8_t const* buffer_end can work.






          share|improve this answer













          C++20 will have std::span, which does what you want:



           Result decode(std::span<uint8_t const> buffer);


          std::span<T> is semantically equivalent to a T* buffer, size_t size.




          In C++17, there are some implementations of a span type which are equivalent to std::span, such as the GSL's gsl::span. See What is a "span" and when should I use one? .



          If you can't use any external libraries, consider writing your own span type, else
          uint8_t const* buffer_begin, uint8_t const* buffer_end can work.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 55 mins ago









          JustinJustin

          13.8k95899




          13.8k95899





















              3














              I agree that mandating vector is inappropriate, and applaud your attempts to make the interface more useful.



              If decode expects a contiguous sequence of uint8_t, the tried-and-tested (and most flexible) solution is just to take a const uint8_t* and a std::size_t (or alternatively two pointers, but pointer and length is more idiomatic).



              From C++20 you can do this with one argument of type std::span<const uint8_t>. Or going back to pointers, if you really want to use modern library tools for the sake of it, you can confuse people with std::experimental::observer_ptr.



              You may also consider making decode a template that accepts any iterator pair, and (if contiguity is needed) mandates, even if only by documentation, that the iterators reflect a contiguous sequence. But making everything a template isn't always what you want, and it isn't always useful.






              share|improve this answer





























                3














                I agree that mandating vector is inappropriate, and applaud your attempts to make the interface more useful.



                If decode expects a contiguous sequence of uint8_t, the tried-and-tested (and most flexible) solution is just to take a const uint8_t* and a std::size_t (or alternatively two pointers, but pointer and length is more idiomatic).



                From C++20 you can do this with one argument of type std::span<const uint8_t>. Or going back to pointers, if you really want to use modern library tools for the sake of it, you can confuse people with std::experimental::observer_ptr.



                You may also consider making decode a template that accepts any iterator pair, and (if contiguity is needed) mandates, even if only by documentation, that the iterators reflect a contiguous sequence. But making everything a template isn't always what you want, and it isn't always useful.






                share|improve this answer



























                  3












                  3








                  3







                  I agree that mandating vector is inappropriate, and applaud your attempts to make the interface more useful.



                  If decode expects a contiguous sequence of uint8_t, the tried-and-tested (and most flexible) solution is just to take a const uint8_t* and a std::size_t (or alternatively two pointers, but pointer and length is more idiomatic).



                  From C++20 you can do this with one argument of type std::span<const uint8_t>. Or going back to pointers, if you really want to use modern library tools for the sake of it, you can confuse people with std::experimental::observer_ptr.



                  You may also consider making decode a template that accepts any iterator pair, and (if contiguity is needed) mandates, even if only by documentation, that the iterators reflect a contiguous sequence. But making everything a template isn't always what you want, and it isn't always useful.






                  share|improve this answer















                  I agree that mandating vector is inappropriate, and applaud your attempts to make the interface more useful.



                  If decode expects a contiguous sequence of uint8_t, the tried-and-tested (and most flexible) solution is just to take a const uint8_t* and a std::size_t (or alternatively two pointers, but pointer and length is more idiomatic).



                  From C++20 you can do this with one argument of type std::span<const uint8_t>. Or going back to pointers, if you really want to use modern library tools for the sake of it, you can confuse people with std::experimental::observer_ptr.



                  You may also consider making decode a template that accepts any iterator pair, and (if contiguity is needed) mandates, even if only by documentation, that the iterators reflect a contiguous sequence. But making everything a template isn't always what you want, and it isn't always useful.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 46 mins ago

























                  answered 51 mins ago









                  Lightness Races in OrbitLightness Races in Orbit

                  295k55479816




                  295k55479816



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55670315%2fhow-should-i-replace-vectoruint8-tconst-iterator-in-an-api%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

                      How to solve knockout JS error in Magento 2 Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?(Magento2) knockout.js:3012 Uncaught ReferenceError: Unable to process bindingUnable to process binding Knockout.js magento 2Cannot read property `scopeLabel` of undefined on Product Detail PageCan't get Customer Data on frontend in Magento 2Magento2 Order Summary - unable to process bindingKO templates are not loading in Magento 2.1 applicationgetting knockout js error magento 2Product grid not load -— Unable to process binding Knockout.js magento 2Product form not loaded in magento2Uncaught ReferenceError: Unable to process binding “if: function()return (isShowLegend()) ” magento 2

                      Nissan Patrol Зміст Перше покоління — 4W60 (1951-1960) | Друге покоління — 60 series (1960-1980) | Третє покоління (1980–2002) | Четверте покоління — Y60 (1987–1998) | П'яте покоління — Y61 (1997–2013) | Шосте покоління — Y62 (2010- ) | Посилання | Зноски | Навігаційне менюОфіційний український сайтТест-драйв Nissan Patrol 2010 7-го поколінняNissan PatrolКак мы тестировали Nissan Patrol 2016рвиправивши або дописавши її