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