4

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;
}
calccrypto
  • 8,583
  • 21
  • 68
  • 99
  • 1
    I'm not sure exactly what you are trying to do, but [here](http://ideone.com/X9fgD) is a fix to your code. You might want to explain more to get a better answer. – Jesse Good May 31 '12 at 00:47
  • 1
    Use `function(func-params)` to specify template arguments when they cannot be deduced - see @Jesse's example. But it's not clear what you wish would happen at `//var = class1();`. – aschepler May 31 '12 at 00:49
  • ah. oops. i forgot about ``. this unfortunatly doesnt solve my problem. i dont know `T` beforehand. i guess i can change my code to do that, but i would prefer to figure out `T` within the function – calccrypto May 31 '12 at 00:52

1 Answers1

3

Have you tried specifying the template arguments explicitly ?

function<uint8_t>(1, str, str, str);

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:

typedef AbstractT* (*CreatorMethod)(std::string, std::string, std::string);
typedef Factory <AbstractT,uint8_t,CreatorMethod> TFactory;

TFactory tfact;

tfact.Register(1, &someCreatorMethod);
tfact.Register(2, &someOtherCreatorMethod);

std::string str = "01234567";

AbstracT* object = tfact.Create(1 str, str, str);
AbstracT* object = tfact.Create(2 str, str, str);
Julien Lebot
  • 3,092
  • 20
  • 32