2016-12-28 2 views
-2

공통 조상으로부터 상속받은 클래스 목록을 반복 할 수 있기를 원합니다.클래스 목록 반복하기

나는 (파이썬 같은 그게 내가에서오고 언어의 같은 구문) 원하는 것을

축소 된 버전이 작동 이런 종류의 일을 선호하는 방법이 아닌 경우

const *Player *PLAYERS[3] = { *PlayerTypeOne, *PlayerTypeTwo, *PlayerTypeThree}; 

int outcome = 0; 

for player in players { 
    if (doThingWithPlayer((&player)(), some, other, variables) == true) { 
     outcome++; 
    } 
} 

가 조언하는 방법에 나는 계속해야한다 매우 환영한다.

내가 피하고 싶은 코드의 종류는 다음과 같습니다 당신은 factory design pattern를 찾고 있습니다

int outcome = 0; 

PlayerTypeOne player_one(); 
if doThingWithPlayer(player_one, some, other, variables){ 
    outcome++; 
} 
PlayerTypeTwo player_two(); 
if doThingWithPlayer(player_two, some, other, variables){ 
    outcome++; 
} 
PlayerTypeThree player_three(); 
if doThingWithPlayer(player_three, some, other, variables){ 
    outcome++; 
} 
+0

클래스의 목록 또는 클래스 인스턴스 (즉, 객체)의리스트 : 당신이 할 수있는 일

사용 메타 프로그래밍인가? – NPE

+1

'object'와'class'라는 용어를 섞어서 사용합니까? –

+0

@NPE 클래스 목록 – muddyfish

답변

1

: 등등

Player *create_by_name(const std::string &what) 
{ 
    if (what == "PlayerTypeOne") 
     return new PlayerTypeOne; 
    if (what == "PlayerTypeTwo") 
     return new PlayerTypeTwo; 

    // ... 
} 

하고 있습니다. 또한 원하는 것은 각 서브 클래스의 생성자에 매개 변수를 제공하는 것입니다.

모든 하위 클래스가 동일한 생성자 매개 변수를 사용하면 이는 간단 해집니다. 매개 변수를 팩토리로 전달하고 생성자에게 전달해야합니다.

생성자에 다른 매개 변수를 지원해야하는 경우 더욱 복잡해집니다. 작게 시작하여 생성자 매개 변수없이 모든 하위 클래스에 대해 동일한 두 개의 객체 만 사용하여 객체에 대한 간단한 팩토리를 구현하는 것이 좋습니다. 기본 원리가 작동하면 복잡한 코너 케이스를 처리하는 것에 대해 걱정할 수 있습니다.

그런 다음 클래스 이름 배열을 가지고 배열을 반복하고 팩토리를 호출하십시오. 이것은 유사 파이썬 코드와 비슷한 결과를 가져야합니다.

+4

원시 포인터 :( –

1

C++에는 내장 된 내성 검사가 없으므로 클래스를 나타내는 개체를 가져 와서 인스턴스를 만들 수 없습니다.

// A list of types 
template <class...> struct pack { }; 

// Calls f with one default-constructed instance of each T 
template <class... Ts, class F> 
void construct_each(pack<Ts...>, F &&f) { 

    // Classic pre-C++17 expansion trick 
    using ex = int[]; 
    (void)ex{(f(Ts{}), void(), 0)..., 0}; 

    // C++17 version 
    // (void)(f(Ts{}), ...); 
} 

// ... 

using Players = pack<PlayerTypeOne, PlayerTypeTwo, PlayerTypeThree>; 

void foo() { 
    int outcome = 0; 

    construct_each(Players{}, [&](auto &&player) { 
     if(doThingWithPlayer(player, some, other, variables)) 
      ++outcome; 
    }); 
} 

See it live on Coliru