how would i create a function that uses templates within itself but not in its arguments? i have a lot of classes that have the same constructors and functions, but do different things within their constructors, so im trying to create a function that can accept a number (this is necessary) to tell a switch which function the templated value should become. how should i do this?
putting the template in the function rather than templating the function itself doesnt work either
this does not work
#include <iostream>
template <typename T> void function(uint8_t s, std::string str1, std::string str2, std::string str3){
T var;
switch (s){
case 1:
// var = class1();
break;
// case 2 ...
// case 3 ...
default:
break;
}
}
int main() {
std::string str = "01234567";
std::cout << function(1, str, str, str) << std::endl;
return 0;
}
Have you tried specifying the template arguments explicitly ?
EDIT:
It is not possible to do exactly what you want, because templates are resolved at compile time, but the arguments of your function are resolved at runtime. So, during compilation, the compile has no idea what the value of ‘s’ is.
For your purpose I think a Factory pattern would be appropriate. See Alexandrescu’s factory method pattern.
Sample usage: