【问题标题】:Conditionally inheriting from either of two classes [duplicate]有条件地从两个类中的任何一个继承[重复]
【发布时间】:2012-12-09 01:47:15
【问题描述】:

可能重复:
Generating Structures dynamically at compile time

我现在面临的情况是,我希望派生类根据条件(在 C++03 中)从 Base1Base2 继承。这意味着,我想实现类似:

// pseudo-C++ code
class Derived : public
    if(condition) Base1    // inherit from Base1, if condition is true
    else Base2             // else inherit from Base2
{ /* */ };

这可能不是一个好的设计,但现实世界并不完美。

我已经在这里搜索了答案,但我不想使用预处理器指令Problems with ifdef based inheritance in C++

我还能如何做到这一点?

【问题讨论】:

标签: c++ inheritance c++03


【解决方案1】:

我找到了使用模板和部分专业化的解决方案。下面的代码可以解决问题:

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

语法看起来不干净,但结果比使用预处理器指令更干净。

【讨论】:

  • 恭喜,你已经彻底改造了std::conditional
  • 好吧,好吧。我没有意识到这一点。正如我提到的,我没有通过搜索找到它。
  • 如果我可以补充,我在 C++03 中重新发明了std::conditional。 :) 感谢您指出了这一点。这促使我尽快阅读有关 C++11 的更多信息。
猜你喜欢
  • 2012-06-23
  • 2013-02-19
  • 2011-09-04
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多