Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Template Instantiation

Tags:

c++

templates

I've got a class template, and I need to declare an object of that class, without defining the type parameters, so that I can define them conditionally later, e.g.:

template<typename T>
class A{
public:
    A(T v){var = v};
    ~A(){};

    T var;
}

int main(){
    A<>* object; // Or sometihng along these lines...?
    if(/* something*/)
        object = new A<float>(0.2f);
    else{
        object = new A<int>(3);
    }
}
like image 670
user965369 Avatar asked Oct 16 '11 14:10

user965369


2 Answers

Well, you certainly can't do that. You'll have to make A derive from another class, for example:

template<typename T>
class A : public B {
public:
    A(T v){var = v};
    ~A(){};

    T var;
}

int main(){
    B* object;
    if(/* something*/)
        object = new A<float>(0.2f);
    else{
        object = new A<int>(3);
    }
}
like image 194
Benjamin Lindley Avatar answered Oct 30 '22 12:10

Benjamin Lindley


The easiest way to do this is to use another function.

template<typename T> void other_stuff(A<T>* object) {
    // use T here
}
int main() {
    if (condition)
        other_stuff(new A<float>(0.2f));
    else
        other_stuff(new A<int>(3));
}

This maintains all type information and does not depend on inheritance. The disadvantage of inheritance is that T cannot appear in any function interfaces, but with this situation it can.

like image 39
Puppy Avatar answered Oct 30 '22 13:10

Puppy