Возможный дубликат:
Динамическое создание структур во время компиляции
Сейчас я сталкиваюсь с ситуацией, когда я хочу, чтобы производный класс наследовал от любого Base1
или же Base2
в зависимости от условия (в C ++ 03). Это означает, что я хочу реализовать что-то вроде:
// pseudo-C++ code
class Derived : public
if(condition) Base1 // inherit from Base1, if condition is true
else Base2 // else inherit from Base2
{ /* */ };
Это, вероятно, не очень хороший дизайн, но реальный мир не идеален.
Я искал здесь ответ, но я не хочу использовать директиву препроцессора Проблемы с наследованием на основе ifdef в C ++.
Как еще я мог достичь этого?
Я разобрался с решением, используя шаблоны и частичную специализацию. Код ниже делает свое дело:
// provide both the required types as template parameters
template<bool condition, typename FirstType, typename SecondType>
class License {};
// then do a partial specialization to choose either of two types
template<typename FirstType, typename SecondType>
class License<true, FirstType, SecondType> {
public: typedef FirstType TYPE; // chosen when condition is true
};
template<typename FirstType, typename SecondType>
class License<false, FirstType, SecondType> {
public: typedef SecondType TYPE; // chosen when condition is false
};
class Standard {
public: string getLicense() { return "Standard"; }
};
class Premium {
public: string getLicense() { return "Premium"; }
};
const bool standard = true;
const bool premium = false;
// now choose the required base type in the first template parameter
class User1 : public License<standard, Standard, Premium>::TYPE {};
class User2 : public License<premium, Standard, Premium>::TYPE {};
int main() {
User1 u1;
cout << u1.getLicense() << endl; // calls Standard::getLicense();
User2 u2;
cout << u2.getLicense() << endl; // calls Premium::getLicense();
}
Синтаксис выглядит нечистым, но результат получается чище, чем при использовании директивы препроцессора.
Других решений пока нет …