【问题标题】:Cannot convert initializer_list to class<int>无法将 initializer_list 转换为 class<int>
【发布时间】:2019-10-05 13:54:13
【问题描述】:

我正在尝试为类模板初始化列表。我是一个新手,在这方面遇到了一些麻烦。 main() 上的错误

#include <iostream>
#include <initializer_list>
#include <stdexcept>

template <class T>
class Storage
{
private:
    int nrOfEl{ 0 };
    T *m_array{};
public:
//...
    Storage(std::initializer_list<T>& list)
        : Storage( static_cast<int>(list.size()) )
    {
        int count{ 0 };
        for (auto& element : list)
        {
            m_array[count] = element;
            ++count;
        }
    }

    ~Storage()
    {
        std::cout << "\nCalling ~Storage()\n";
        delete[] m_array;
    }

    T& operator[](const int &index)
    {
        if (index >= nrOfEl || index < 0)
            throw std::out_of_range("OUT OF BOUNDS");
        return *m_array[index];
    }

    Storage& operator=(std::initializer_list<T>& list)
    {
        int length{ static_cast<int>(list.size()) };
        if (length != nrOfEl)
        {
            delete[] m_array;
            nrOfEl = length;
            m_array = new int[length];
        }

        int count = 0;
        for (int element : list)
        {
            m_array[count] = element;
            ++count;
        }

        return *this;
    }
//...
};

int main()
{
    Storage<int> ints { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
        //error here
    return 0;
}

错误 C2440:“正在初始化”:无法从“初始化程序列表”转换为“存储”

注意:没有构造函数可以采用源类型,或者构造函数重载决议不明确

【问题讨论】:

    标签: c++ templates initializer-list stdinitializerlist


    【解决方案1】:

    除其他答案外的注意事项:没有理由将std::initializer_list 传递给const&amp;,它只是一对指针(或指针和大小)。您可以按值传递它,就像在标准库中所做的那样。

    【讨论】:

    • 最佳答案。如果我能多次投票就好了!
    【解决方案2】:

    main() 中,您的初始化列表被构造为一个右值,因此传递引用将失败。但是,通过 const-reference 传递将起作用。您应该允许构造函数接受 const-reference 列表:

    Storage(const std::initializer_list<T>& list)
    //      ^^^^^
        : Storage( static_cast<int>(list.size()) )
    {
        int count{ 0 }; 
        for (const auto& element : list)    // const here too
        {
            m_array[count] = element;
            ++count;
        }
    }
    

    您还应该使用operator= 同样更改参数。

    【讨论】:

    • C++ const 正确性:是的,它很重要!
    【解决方案3】:

    你有两个问题:

    1. 您正在通过非常量引用将初始化程序列表传递给 Storage() 构造函数。
    2. 您尚未定义 Storage(int) 构造函数。

    这应该可以解决这两个问题:

    Storage(std::initializer_list<T> const& list)
        : nrOfEl( static_cast<int>(list.size()) )
    { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多