c++ - 是否可以在对象实例化期间定义 std::array 类成员的元素计数?

标签 c++ c++11 stdarray

我想编写一个类,其对象是具有固定列数的字符串表。由于列数在对象的生命周期内保持不变,我决定从 std::array 容器中声明每一行对象。

下面的代码是我尝试编写这样一个类。

class Table
{
    public:
        Table(size_t ColumnCount)   // LINE 45
        {
            // The constant 'N' in the template definitions
            // will be equal to the 'ColumnCount' parameter.
        }
        template <uint64_t N>
        void AddRow(const std::array<std::wstring, N> & NewRow)
        {
            Rows.push_back(NewRow);
        }
    private:
        template <uint64_t N>       // LINE 55
        std::list<std::array<std::wstring, N>> Rows;
};

Table mytable(5);   // Create a table with 5 columns

我收到错误(在 Visual Studio 2012 中):

Line 55: error C3857: 'Table::Rows': multiple template parameter lists are not allowed
Line 45: error C2512: 'std::list<std::array<std::wstring,N>>' : no appropriate default constructor available

是否可以让这段代码运行?

最佳答案

是的,你可以。只需将您的模板参数放在类的顶部,而不是成员声明的位置,就像这样:

template <uint64_t N>
class Table
{
    public:
        Table()   // LINE 45
        {
            // The constant 'N' in the template definitions
            // No need for an external variable
        }
        void AddRow(const std::array<std::wstring, N> & NewRow)
        {
            Rows.push_back(NewRow);
        }
    private:
        // Not here
        std::list<std::array<std::wstring, N>> Rows;
};

然后要使用它,您只需执行 Table<5> stuff;这将使它成为一个编译时间常量。您的代码不起作用,因为您不能为单个成员设置模板参数,因为它们必须位于类声明中。

关于c++ - 是否可以在对象实例化期间定义 std::array 类成员的元素计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003957/

相关文章:

c++ - 默认参数和可变参数函数

c++ - 使用显式实例化设置类模板的方法

c++ - 如何将 std::string 转换为 v8 的 Local<string>

c++ - 在 C++11 中的线程之间高效安全地传递不可变对象(immutable对象)

c++ - boost::unordered_set of char16_t 字符串

c++ - 使用 std::vector 进行 std::array 初始化

c++ - 我的 vector 在通过构造函数传递后怎么会发生变化?

c++ - 模板化函数和类中的 T&&

c++ - 优雅地声明 2(甚至多)维 std::array

c++ - 尝试从 std::array 将 .data() 编译为 c++20 中的 constexpr 函数时出错