//my_initializer_list.h
namespace std
{
template <class T>
class my_initializer_list
{
public:
using value_type = T;
using reference = const T&;
using const_reference = const T&;
using size_type = size_t;
my_initializer_list() noexcept : __begin(nullptr), __size(0) {}
my_initializer_list(const T* __b, size_t __s) noexcept : __begin(__b), __size(__s){}
const T* begin() const noexcept {return __begin;}
const T* end() const noexcept {return __begin+ __size;}
size_t size() const noexcept { return __size;}
private:
const T* __begin;
size_t __size;
};
}
int main()
{
int array[] = {1,2,3};
std::my_initializer_list<int> a = std::my_initializer_list<int>(array,sizeof(array)/sizeof(array[0]));
for (const int& value : a)
{
std::cout << value << " ";
}
return 0;
}
使用
#include <iostream>
#include <my_initializer_list.h>
class MyArray
{
public:
MyArray(std::my_initializer_list<int> values)
{
size_ = values.size();
data_ = new int[size_];
int i = 0;
for(auto value : values)
{
data_[i++] = value;
}
}
void print()
{
for (int i = 0; i < size_; ++i) {
std::cout << data_[i] << " ";
}
std::cout << std::endl;
}
private:
int* data_;
size_t size_;
};
int main()
{
int array[] = {1,2,3,4};
MyArray arr = MyArray(std::my_initializer_list<int>(array,sizeof(array)/sizeof(array[0])));
//等价于
MyArray arr = {1, 2, 3, 4};
arr.print();
return 0;
}