Is it possible to define element count of an std::array class member during object instantiation?

StackOverflow https://stackoverflow.com/questions/18003957

  •  04-06-2022
  •  | 
  •  

Question

I want to write a class whose objects will be string tables with fixed column count. Since the column count will stay fixed during an object's life time, I decided to declare each row object from std::array containers.

The code below is my attempt to write a class like this.

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

I get the errors (in 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

Is it possible to make this code run?

Était-ce utile?

La solution

Yes you can. Just put your template parameter on top of the class instead of where the member declaration is like so:

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;
};

then to use it you just do Table<5> stuff; This would make it a compile time constant. Your code doesn't work because you can't have template parameters for individual members as they have to be in the class declaration instead.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top