2011-10-24 7 views
5

Jeśli mam interfejs i wiele klas, które implementują ten interfejs, czy mogę teraz przekazać jako argument tylko typ klasy, a nie obiekt?Typ klasy C++ jako argument

coś takiego:

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 dziedziczy IFrame

Odpowiedz

12

Nazywa się "Template".

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

Musisz zadzwonić to w ten sposób:

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

edytowany

Można również spróbować, aby upewnić się, że tylko tworzenie wystąpień Interface:

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

edytuj do edycji

Próbowałem ten kod testowy:

#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(); 
} 

działa dokładnie tak, jak oczekiwano. Musisz mieć inne błędy kodowania w definicjach klas. Debuguj go, nie ma to nic wspólnego z pierwotnym pytaniem.

+0

spójrz na edycję – Vladp

+0

@vladp - spojrzał na nią. – littleadv