Ant*_*nio 6 c++ templates c++98
假设我有一个常量值(可能是一些枚举类型).假设我有很多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
Run Code Online (Sandbox Code Playgroud)
那么,是否可以在编译时根据常数选择一个类?
一般的问题是我试图根据表选择一个仿函数,其中索引是一个枚举.如果可能的话,我想避免多态性.
编辑:对于这个项目我不能使用C++ 11,无论如何,感谢谁在那个环境中回答,无论如何都知道非常有趣.
编辑2:一般来说,我可以有两个以上的目标类,我编辑了我的问题
0x4*_*2D2 11
这不是唯一的方法,但我希望你的目的可以接受:
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;
Run Code Online (Sandbox Code Playgroud)
更新:要在没有C++ 11功能的情况下执行相同操作,您应该创建C一个类,其typedef成员类型等于上面对应的类型别名:
template <int N>
struct C
{
typedef typename choices<N>::type type;
};
// ...
C<1>::type anInstanceOfA;
C<2>::type anInstanceOfB
Run Code Online (Sandbox Code Playgroud)
使用LSP和普通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;
Run Code Online (Sandbox Code Playgroud)
由于C++中的公共继承满足IS-A规则,anInstanceOfA因此IS-A C<1>对象和IS_AN A对象都是如此.