Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class type as argument

If I have an interface and many classes that implement this interface, can I now pass as argument only the type of the class and not the object?

something like this:

Interface *creatClass(class : Interface){
    return new class();
}

EDIT:

template <class T>
IFrame *creatClass(){
    return new T();
}

void dfg(){
    IFrame *lol = creatClass<Button>();
}

error C3206: 'creatClass' : invalid template argument for 'Dist_Frame', missing template argument list on class template 'Button'

PS. Button inherits IFrame

like image 669
Vladp Avatar asked Oct 24 '11 18:10

Vladp


1 Answers

It's called "Template".

template <class T>
T *creatClass(){
    return new T();
}

You'll have to call it this way:

class InterfaceImpl : public Interface {...};
// ...
InterfaceImpl *newImpl = creatClass<InterfaceImpl>();

edited

You can also try this, to ensure you only create instances of Interface:

template <class T>
Interface *creatClass(){
    return new T();
}

edit to your edit

I tried this test code:

#include <iostream>
using namespace std;

class IFrame{
   public:
      virtual void Create() =0;
};

class Button : public IFrame{
    public:

       virtual void Create(){ cout << "In Button" << endl;};
};

template <class T>
IFrame *creatClass(){
    return new T();
}


int main()
{
    IFrame *lol = creatClass<Button>();
    lol->Create();
}

Works exactly as expected. You must have some other coding errors in your class definitions. Debug it, it has nothing to do with your original question.

like image 179
littleadv Avatar answered Sep 28 '22 04:09

littleadv