我可以在编译时使用一个常数来选择一个类,可能使用模板吗? [英] May I use a constant number to choose a class at compile time, possibly using templates?

查看:28
本文介绍了我可以在编译时使用一个常数来选择一个类,可能使用模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个常量值(可能是某种枚举类型).假设我有很多类 A、B、D 等.

Let's say I have a constant value (possibly of some enum type). Let's say I have many classes A, B, D, etc.

我可以拥有这样的东西吗?

Can I have something like this?

C<1> anInstanceOfA; //This will be of type A
C<2> anInstanceOfB; //This will be of type B
C<3> anInstanceOfD; //This will be of type D

那么,是否可以在编译时根据一个常数来选择一个类?

So, is it possible to select a class based on a constant number at compile time?

一般的问题是我试图根据一个表选择一个函子,其中索引是一个枚举.如果可能,我想避免多态性.

The general problem is that I am trying to select a functor based on a table, in which the index is an enum. I would like to avoid polymorfism if possible.

对于这个项目,我不能使用 C++11,无论如何感谢在那个上下文中回答的人,无论如何知道很有趣.
一般我可以有2个以上的目标类,我已经编辑了我的问题

For this project I cannot use C++11, thanks anyway to who answered in that context, very interesting to know anyway.
Edit 2: In general I can have more than 2 target classes, I have edited my question

推荐答案

使用 LSP 和普通 C++98:

Using the LSP and plain C++98:

template <int N> class C;
template <> class C<1> : public A {};
template <> class C<2> : public B {};
template <> class C<3> : public D {};

C<1> anInstanceOfA;

由于 C++ 中的公共继承满足 IS-A 规则,anInstanceOfA IS-A C<1> 对象和 IS_AN A 对象.

Since public inheritance in C++ satisfies the IS-A rule, anInstanceOfA both IS-A C<1> object and IS_AN A object.

这篇关于我可以在编译时使用一个常数来选择一个类,可能使用模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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