我可以在编译时使用常量来选择类(可能使用模板)吗?

2024-01-14

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

我可以有这样的东西吗?

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

那么,是否可以在编译时根据常量来选择类呢?

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

Edit:对于这个项目,我不能使用 C++11,无论如何要感谢在该上下文中回答的人,无论如何,知道这一点非常有趣。
Edit 2:一般来说,我可以有超过 2 个目标类别,我已经编辑了我的问题


这不是唯一的方法,但我希望您可以接受:

struct A { };
struct B { };

template <int N>
struct choices;

template <>
struct choices<1> { typedef A type; };

template <>
struct choices<2> { typedef B type; };

template <int N>
using C = typename choices<N>::type;

更新:要在没有 C++11 功能的情况下执行相同的操作,您应该C一个类有一个typedef成员类型等于上面对应的类型别名:

template <int N>
struct C
{
    typedef typename choices<N>::type type;
};

// ...
C<1>::type anInstanceOfA;
C<2>::type anInstanceOfB
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我可以在编译时使用常量来选择类(可能使用模板)吗? 的相关文章

随机推荐