使用值列表初始化模板数组 在标准C++中,我们可以写: int myArray[5] = {12, 54, 95, 1, 56};

使用值列表初始化模板数组 在标准C++中,我们可以写: int myArray[5] = {12, 54, 95, 1, 56};,c++,arrays,templates,C++,Arrays,Templates,我想用一个模板写同样的东西: Array<int, 5> myArray = {12, 54, 95, 1, 56}; Array myArray={12,54,95,1,56}; 假设 template <class Type, unsigned long N> class Array { public: //! Default constructor Array(); //! Destructor virtual ~Array(

我想用一个模板写同样的东西:

Array<int, 5> myArray = {12, 54, 95, 1, 56};
Array 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];
};
模板
类数组
{
公众:
//!默认构造函数
数组();
//!析构函数
虚拟数组();
//!用于获取项目计数
//!@返回物品计数
无符号长getCount()常量;
//!用于访问指定项上的引用
//!@param要访问的项目的项目
//!@返回指定项目的引用
类型和运算符[](常量无符号长p_knIndex);
//!用于访问指定项上的常量引用
//!@param要访问的项目的项目
//!@返回指定项目的常量引用
常量类型和运算符[](常量无符号长p_knIndex)常量;
私人:
//!数组集合
类型m_数组[N];
};

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

这在C++0x中可以使用。目前,没有办法做到这一点


没有这个,你能得到的最接近的东西就是使用。

你说得对。在当前的标准C++中,这是不可能的。然而,对于下一个标准(c++0x),初始值设定项列表就可以做到这一点

其实很琐碎;只需删除构造函数和 公开数据成员。模板问题是红色的 赫林;同样的规则适用于任何类:如果它是 聚合,可以使用聚合初始化;如果不是, 你不能

--
James Kanze

我的解决方案是编写一个类模板,将传递给构造函数的所有值累加起来。下面是如何立即初始化
数组的方法:

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

1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10

您自己可以在ideone上查看在线演示:

另一个解决方案,它不需要
加法器
类模板。现在您可以执行以下操作:

int main() {

        Array<int, 10> array;
        array = 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;
}

以下是完整的解决方案:

如果我将数据成员设置为public,这将破坏模板类实现的访问安全。@chris Yes。如果隐藏元素非常重要,则不能使用此格式。在很多情况下,数组是抽象的一部分,因此公开它不是问题。在其他情况下,数组是完全隐藏的,因此即使想要使用聚合初始化也违反了抽象。在这两个极端之间的情况下,你有点被卡住了。@nawaz-ideone链接断了。你能把密码寄出去吗?thanks@Koushik当前位置我发布了两个解决方案。请参阅另一个实现了
数组的。你可以用它在ideone上进行实验。:-)@纳瓦兹:事实上,我想我知道你是如何实现的,但我只是想确认一下。:-)非常好,这是我第一次看到有人超载,。+1。
1
2
3
4
5
6
7
8
9
10