假设我有一个常量值(可能是某种枚举类型)。 假设我有很多类 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
那么,是否可以在编译时根据一个常量来选择类呢?
一般的问题是我试图根据表选择一个仿函数,其中索引是一个枚举。如果可能,我想避免多态性。
编辑:对于这个项目,我不能使用 C++11,无论如何要感谢在那个上下文中回答的人,无论如何都非常有趣。
编辑 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
关于c++ - 我可以在编译时使用一个常量来选择一个类,可能使用模板吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17950349/