我想写一个类,它的对象将是具有固定列数的字符串表。由于列计数在对象的生命周期内保持不变,所以我决定从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;
。这将使它成为编译时间常数。您的代码不起作用,因为您不能为单个成员设置模板参数,因为它们必须在类声明中。