有条件地从两个类之一继承 [英] Conditionally inheriting from either of two classes

查看:65
本文介绍了有条件地从两个类之一继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在编译时动态生成结构

Possible Duplicate:
Generating Structures dynamically at compile time

我现在正面临一种情况,我希望派生类根据条件(在C ++ 03中)从Base1Base2继承.这意味着,我想实现类似以下内容:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆