我想编写一个类,其对象是具有固定列数的字符串表。由于列数在对象的生命周期内保持不变,我决定从 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/