模板数组初始化与值列表 [英] Template array initialization with a list of values

查看:171
本文介绍了模板数组初始化与值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在标准C ++中,我们可以这样写:

In standard c++ we can write :

int myArray[5] = {12, 54, 95, 1, 56};

我还想写同样的事情用一个模板:

I would like to write the same thing with a template :

Array<int, 5> myArray = {12, 54, 95, 1, 56};

假设

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];
};

我认为这是不可能的,但可能有一个棘手的方式做到这一点!

I thinks it is not possible but may be there's a tricky way to do it !

推荐答案

我的解决方法是编写累积其中获得传递给构造函数的所有值类模板。这里是你如何initizalize你的阵列现在

My solution is to write a class template that accumulates all the values which get passed to the constructor. Here is how you can initizalize your Array now:

Array<int, 10> array = (adder<int>(1),2,3,4,5,6,7,8,9,10);

的实施加法器与完整演示如下图所示:

The implementation of adder is shown below with complete demonstration:

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;
}

输出:

1
2
3
4
5
6
7
8
9
10

请参阅在线演示在ideone自己: http://www.ideone.com/KEbTR

See the online demo at ideone yourself : http://www.ideone.com/KEbTR

这篇关于模板数组初始化与值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆