chr*_*ris 3 c++ arrays templates
在标准 C++ 中我们可以这样写:
int myArray[5] = {12, 54, 95, 1, 56};
Run Code Online (Sandbox Code Playgroud)
我想用模板写同样的东西:
Array<int, 5> myArray = {12, 54, 95, 1, 56};
Run Code Online (Sandbox Code Playgroud)
假如说
template <class Type, unsigned long N>
class Array
{
public:
//! Default constructor
Array();
//! Destructor
virtual ~Array();
//! Used to get the item count
//! @return the item count
unsigned long getCount() const;
//! Used to access to a reference on a specified item
//! @param the item of the item to access
//! @return a reference on a specified item
Type & operator[](const unsigned long p_knIndex);
//! Used to access to a const reference on a specified item
//! @param the item of the item to access
//! @return a const reference on a specified item
const Type & operator[](const unsigned long p_knIndex) const;
private:
//! The array collection
Type m_Array[N];
};
Run Code Online (Sandbox Code Playgroud)
我认为这是不可能的,但可能有一个棘手的方法来做到这一点!
我的解决方案是编写一个类模板来累积传递给构造函数的所有值。以下是初始化Arraynow 的方法:
Array<int, 10> array = (adder<int>(1),2,3,4,5,6,7,8,9,10);
Run Code Online (Sandbox Code Playgroud)
其实现adder如下图,完整演示:
template<typename T>
struct adder
{
std::vector<T> items;
adder(const T &item) { items.push_back(item); }
adder& operator,(const T & item) { items.push_back(item); return *this; }
};
template <class Type, size_t N>
class Array
{
public:
Array(const adder<Type> & init)
{
for ( size_t i = 0 ; i < N ; i++ )
{
if ( i < init.items.size() )
m_Array[i] = init.items[i];
}
}
size_t Size() const { return N; }
Type & operator[](size_t i) { return m_Array[i]; }
const Type & operator[](size_t i) const { return m_Array[i]; }
private:
Type m_Array[N];
};
int main() {
Array<int, 10> array = (adder<int>(1),2,3,4,5,6,7,8,9,10);
for (size_t i = 0 ; i < array.Size() ; i++ )
std::cout << array[i] << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)
亲自观看 ideone 的在线演示: http: //www.ideone.com/KEbTR