what to do when return type is determined in runtime in c++? -


here scenario: have column-majored matrix file in binary format loaded, matrix may short, int, double, etc. conceptually needs done:

mat<xxx> loadfile(std::string filename) {     std::string mattype = gettype(filename);     mat<mattype> mat;     mat.load(filename);     return mat; } 

but problem is, since don't know return type, cannot define function in first place.

you cannot this. in simplest form, loadfile should template that

template<typename t> mat<t> loadfile(std::string filename) {     mat<t> mat;     mat.load(filename);     return mat; } 

so user explicitly specifies type by

mat<int> mat = loadfile<int>("filename.mat"); 

now if file has embedded information type, can @ runtime e.g. throw exception if t not consistent actual stored type.

if number of possible types limited, use template function run<t> specify need data (the algorithm) , choose depending on input, e.g.

is_type_real(filename) ? run<double>(filename) : run<int>(filename); 

in case, compiler instantiates possible (two here) algorithm versions (specializations) @ compile-time, , appropriate 1 called @ run-time.

this idea can extended look-up table of pointers-to-function, might close had in mind:

template<typename t> void run(std::string filename) {    mat<t> mat = loadfile<t>(filename);     // run algorithm type t }  using fun = void(*)(std::string);  fun lookup[4] = { run<int>, run<long>, run<float>, run<double> };  enum matrix_type { int, long, float, double };  matrix_type get_type(std::string filename) {    // read type file, return matrix_type };  int main() {     std::string filename = "filename.mat";     matrix_type type = get_type(filename);     lookup[type](filename); } 

in passing run-time compile-time world, think close can get. can further organized, see e.g. here , this question. wanted give idea.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -