C++ Generic Table Data Structure
Let's have a bunch of tables. Tables have columns. Each column hold data of its kind. I am looking for a structure for a generic table that would allow me to access elements at given coordinates and access individual columns.
My idea was to provide a common interface that would be implemented in children. Children would use vectors to store individual columns. There are like four tables I am working with, so I could have one object for each of them.
class Data {
template < typename T >
virtual T getElement(unsigned int row, unsigned int column) const = 0;
template < typename T >
virtual void setElement(unsigned int row, unsigned int column, T value) = 0;
template < typename T >
virtual std::vector< T > getColumn(unsigned int column) const = 0;
template < typename T >
virtual void setColumn(unsigned int column, std::vector< T > values) = 0;
};开发者_如何学运维
The problem is obviously in "error: templates may not be ‘virtual’". What would be the best way to attack this problem? I would like to avoid using external libraries.
Petr
Make the class template, like this:
template<typename T>
class Data {
virtual T getElement(unsigned int row, unsigned int column) const = 0;
virtual void setElement(unsigned int row, unsigned int column, T value) = 0;
virtual std::vector< T > getColumn(unsigned int column) const = 0;
virtual void setColumn(unsigned int column, std::vector< T > values) = 0;
};
This way you make your functions generic, simultaneously making the compiler happy as well.
This is an old question, but for folks still looking around:
You could implement a generic table using templates and modern C++. By defaulting the template arguments, you get a usable table, but you also get the ability to strongly type it. std::any
allows us to mix types in the table as well. You can use this example to add your own API, but it is usable as-is.
#include <any>
#include <map>
#include <iostream>
template<typename R = int, typename C = int, typename T = std::any>
class Table
{
public:
std::map<C, T>& operator[](R x)
{
return this->Data[x];
}
std::map<R, std::map<C, T>> Data;
};
int main()
{
Table t;
t[0][0] = std::string("foo");
t[0][1] = int(2112);
std::cout << std::any_cast<std::string&>(t[0][0]) << ", ";
std::cout << std::any_cast<int>(t[0][1]) << std::endl;
return 0;
}
Running version here: https://wandbox.org/permlink/WWYMppvweGNiW5Tm
精彩评论