johanatan wrote:
johanatan said:
I have two functions that are nearly identical (one validates a row
and one validates a table). Since a table is open-ended (i.e., can
have infinite rows) but a row is finite, there is one addtional line
of code in the ValidateRow func which asserts that the row data has
the appropriate number of cells.
I would like to make these a template function with a specialization
for the row that asserts the one extra condition and then calls the
generic template function. Is this possible?
Thanks,
Jonathan
I have two functions that are nearly identical (one validates a row
and one validates a table). Since a table is open-ended (i.e., can
have infinite rows) but a row is finite, there is one addtional line
of code in the ValidateRow func which asserts that the row data has
the appropriate number of cells.
I would like to make these a template function with a specialization
for the row that asserts the one extra condition and then calls the
generic template function. Is this possible?
Yes, but you probably want an overload rather than a specialization.
It sounds like the code to validate a row is identical (except for the
assertion) to the code that validates a table. Is this correct? If so,
you can do something like:
#include <cassert>
#include <cstdlib>
#include <string>
#include <vector>
std::size_t const row_size = 42;
typedef std::string cell_type;
typedef std::vector<cell_type> row_type;
typedef std::vector<row_type> table_type;
/* Works for tables and rows. */
template<typename T>
void validate(T const& t) {
// ...
}
void validate(row_type const& row) {
assert(row.size() == row_size);
validate<row_type>(row);
}
int main() {
row_type row(row_size );
table_type table;
table.push_back(row);
/* Invokes an instantiation of the template. */
validate(table);
/* Invokes the row-specific overload, then
* an instantiation of the template. */
validate(row);
}
If you know the row's size at compile time, you might want to replace
the row class with a template, so that the size can be a template parameter.