Last active
August 29, 2015 14:22
-
-
Save beyondwdq/695c6ac4c6ee900637ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//There are 3 files: seq.h seq.cc main.cc | |
//Compile with: g++ -std=c++11 main.cc seq.cc | |
//-------- seq.h ------------ | |
#include <stdlib.h> | |
#include <string.h> | |
#include <limits> | |
#include <cassert> | |
#include <initializer_list> | |
template <typename T, size_t N> | |
class MyArray | |
{ | |
public: | |
typedef T value_type; | |
MyArray() {} | |
MyArray(std::initializer_list<T> l) { | |
assert (l.size() == N); | |
size_t i = 0; | |
for (auto &v : l) { | |
data_[i] = v; | |
++i; | |
} | |
} | |
MyArray(void *data) | |
{ | |
memcpy(&data_, data, sizeof(T) * N); | |
} | |
T* data() { return data_; } | |
const T* data() const { return data_; } | |
T& operator [](size_t i) { return data_[i]; } | |
const T& operator [](size_t i) const { return data_[i]; } | |
private: | |
T data_[N]; | |
}; | |
// Here we introduce the concept of Sequence, which supports operator [] and has function sizeOfSeq() implemented for it. | |
// Return size of a sequence | |
template <typename TSeq> | |
constexpr size_t sizeOfSeq(const TSeq &seq); | |
// Return the maxinum value of the elements in a sequence | |
template <typename T> | |
auto maxInSeq( const T & seq ) -> T::value_type | |
{ | |
typedef T::value_type value_type; | |
value_type v = std::numeric_limits<value_type>::min(); | |
for (size_t i=0; i<sizeOfSeq(seq); ++i) { | |
if (seq[i] > v) v = seq[i]; | |
} | |
return v; | |
} | |
//-------- seq.cc ------ | |
#include "seq.h" | |
template <typename T, size_t N> | |
constexpr size_t sizeOfSeq(const MyArray<T, N> &seq) | |
{ | |
return N; | |
} | |
//------- main.cc ---------- | |
#include <iostream> | |
#include "seq.h" | |
using namespace std; | |
int main(int argc, const char *argv[]) | |
{ | |
const char *buf = "hello world"; | |
MyArray<char, strlen(buf)+1> arr1(buf); | |
cout << maxInSeq(arr1) << endl; | |
MyArray<int, 5> arr2{0,1,2,3,4}; | |
cout << maxInSeq(arr2) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment