F
Fei Liu
Hi Group, I've got a problem I couldn't find a good solution. I am
working with scientific data files in netCDF format. One of the
properties of netCDF data is that the actual type of data is only known
at run time. Therefore a lot of template based trick isn't too useful.
Considering
datafile
float x(3) 3.5, 2.5, 8.9
double y(3) 2.7, -2.3, 1.2
int z(3) 5, 2, 3
Suppose in my code, I need to write a summation function and return the
result, I could do
template <class T>
T sum(T * data, size_t n);
This is all good and dandy, but in the calling subroutine I am stuck
because at compile I have no priori knowledge of actual data type
contained in the data file, thus I must rely on switch/case code based
on what may be contained in the data file during run time. Consider:
void sum_caller(){
mytype type = datafile.getline(i).type
switch(type){
case float_type:
float ret = sum(datafile.getline(i).data);
do_something(ret);
case double_type:
float ret = sum(datafile.getline(i).data);
...
....
}
I cannot declare 'template <class T> void sum_caller();' because only
within sum_caller, the type information is available. (you could argue
I can declare sum_caller template based, but that's not the point. At
some point, the type information becomes available and appropriate
action can be taken). Is there a design pattern or implementation
strategy that can help me with this dilemma and thus avoid switch/case
based code altogether? Thanks!
working with scientific data files in netCDF format. One of the
properties of netCDF data is that the actual type of data is only known
at run time. Therefore a lot of template based trick isn't too useful.
Considering
datafile
float x(3) 3.5, 2.5, 8.9
double y(3) 2.7, -2.3, 1.2
int z(3) 5, 2, 3
Suppose in my code, I need to write a summation function and return the
result, I could do
template <class T>
T sum(T * data, size_t n);
This is all good and dandy, but in the calling subroutine I am stuck
because at compile I have no priori knowledge of actual data type
contained in the data file, thus I must rely on switch/case code based
on what may be contained in the data file during run time. Consider:
void sum_caller(){
mytype type = datafile.getline(i).type
switch(type){
case float_type:
float ret = sum(datafile.getline(i).data);
do_something(ret);
case double_type:
float ret = sum(datafile.getline(i).data);
...
....
}
I cannot declare 'template <class T> void sum_caller();' because only
within sum_caller, the type information is available. (you could argue
I can declare sum_caller template based, but that's not the point. At
some point, the type information becomes available and appropriate
action can be taken). Is there a design pattern or implementation
strategy that can help me with this dilemma and thus avoid switch/case
based code altogether? Thanks!