有条件地从两个类之一继承 [英] Conditionally inheriting from either of two classes
问题描述
可能重复:
在编译时动态生成结构
Possible Duplicate:
Generating Structures dynamically at compile time
我现在正面临一种情况,我希望派生类根据条件(在C ++ 03中)从Base1
或Base2
继承.这意味着,我想实现类似以下内容:
I am now facing a situation where I want a derived class to inherit from either Base1
or Base2
depending on a condition (in C++03). This means, I want to implement something like:
// pseudo-C++ code
class Derived : public
if(condition) Base1 // inherit from Base1, if condition is true
else Base2 // else inherit from Base2
{ /* */ };
这可能不是一个好的设计,但现实世界并不完美.
This is likely not a good design, but the real world is not perfect.
I have searched here for an answer, but I do not want to use a preprocessor directive Problems with ifdef based inheritance in C++.
我还能怎么实现呢?
推荐答案
我使用模板和部分专业化解决方案.下面的代码可以达到目的:
I figured out the solution using templates and partial specialization. The below code does the trick:
// 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();
}
语法看起来不干净,但结果比使用预处理指令更干净.
The syntax looks unclean, but the result is cleaner than using preprocessor directive.
这篇关于有条件地从两个类之一继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!