可能的重复:
在编译时动态生成结构 https://stackoverflow.com/questions/11376149/generating-structures-dynamically-at-compile-time
我现在面临的情况是我希望派生类继承自Base1
or 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
{ /* */ };
这可能不是一个好的设计,但现实世界并不完美。
我在这里搜索答案,但我不想使用预处理器指令C++ 中基于 ifdef 的继承问题 https://stackoverflow.com/questions/7646820/problems-with-ifdef-based-inheritance-in-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();
}
语法看起来不干净,但结果比使用预处理器指令更干净。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)