Skip to content

Instantly share code, notes, and snippets.

@GitBubble
Created March 20, 2020 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitBubble/3841b253e5c98139cb73c49811f16ec6 to your computer and use it in GitHub Desktop.
Save GitBubble/3841b253e5c98139cb73c49811f16ec6 to your computer and use it in GitHub Desktop.
template_tricks
```
#include <string.h>
#include <memory> // for std::unique_ptr
#include <mutex> // for std::mutex
#include <iterator>
template <class T, class elem_type = class T::value_type>
class ring_iterator; // forward declaration
template <class T, size_t N>
class ring {
public:
typedef size_t size_type;
typedef T value_type;
private: // don't change order of definitions
size_type cap_; // the capacity of the array
size_type size_; // the number of elements in the array
uint8_t mask_;
std::unique_ptr<T[]> array_{nullptr};
size_type head_; // read/consume/front
size_type tail_; // write/produce/back
bool empty_; // true if empty
std::mutex mutex_{};
public:
ring(uint8_t m): cap_{N}, size_{}, mask_{m}, array_{std::unique_ptr<T[]>(new T[cap_])}, head_{}, tail_{}, empty_{true} { memset(array_.get(), 0, (size_type)cap_ * sizeof(T)); }
friend class ring_iterator<T, class T::value_type>; // here's the friending
};
template <class T, class elem_type>
class ring_iterator {
public:
typedef size_t size_type;
typedef T value_type;
private:
T *ring_;
size_type offset_;
public:
ring_iterator(T *r, size_type o) : ring_{r}, offset_{o} {
}
};
int main(int argc, char* argv[]) {
uint8_t t = 0; // usually it's a bit mask
ring<uint8_t, 8> ring(t); // this line causes the trouble
//...
return 0;
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment