C++ 我可以在编译时使用一个常量来选择一个类吗?

C++ 我可以在编译时使用一个常量来选择一个类吗?,c++,templates,c++98,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 caninstanceofa//这将是A型的 C一个实例fb//这将是B型的 C.抗药性FD//这

假设我有一个常量值(可能是某种枚举类型)。 比如说我有很多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
caninstanceofa//这将是A型的
C一个实例fb//这将是B型的
C.抗药性FD//这将是D型的
那么,是否可以在编译时基于常量选择一个类

一般的问题是,我试图基于一个表选择一个函子,其中的索引是一个枚举。如果可能的话,我想避免多摩门教

编辑:对于这个项目,我不能使用C++11,无论如何要感谢在这个上下文中回答问题的人,无论如何,知道这个问题非常有趣。

编辑2:一般来说,我可以有两个以上的目标类,我已经编辑了我的问题

这是一个相当简单的元函数:

template <int N>
struct C {
  typedef typename std::conditional<N == 1,A,B>::type type;
};

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

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;

使用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;
模板类C;
模板类C:公共A{};
模板类C:公共B{};
模板类C:公共D{};
C.抗静电剂;

由于C++中的公共继承满足IS-A规则,<>代码> ANSTANISOFA< <代码>都是As>代码> C<代码> >对象,而ISSAN <代码> A<代码>对象.

您甚至可以嵌套<代码> STD::条件< /代码>以节省空间。我不会评论它是否能独立地输入每个Type,对不起,我应该已经指定了(我现在),我不能使用C++。11@Antonio:
std::conditional
你自己写并不难,它的实现也不依赖于任何C++11功能。@Antonio有一个C++03实现,它为您提供了
conditional
。如果您不想实现它,Boost也有类似的功能。我相信它的语法非常接近std::conditional。也许你会读一读“工厂模式”,你会说另一种语言:),但是这个解决方案确实非常优雅!供我使用的几个链接:。。。而且,我找不到关于IS-A的任何信息……为了让它编译,我添加到add
{}
,获得
模板类C:public A{}。。。对吗?@Antonio是的,没错。@Antonio:在面向对象编程中,反复出现的设计问题之一是“组合还是继承”?更简单的术语是“代码> FoHas-Bar < /C> >与 Foo-A Bar ,在C++中,区分为成员与基类。@安东尼奥:一旦没有一个默认构造函数的类包含在一个类中,或者使用任何参数化构造函数,它就不再那么优雅了。您必须将可能需要的任何构造函数复制到您的专业中。0x499602D2解决方案不存在此问题。幸运的是,C++11为这个问题提供了优雅的解决方案。谢谢!(+1当然)最后,我将选择MSalters answer作为更紧凑的,因为它在实例化时保存::type
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;
template <int N>
struct C
{
    typedef typename choices<N>::type type;
};

// ...
C<1>::type anInstanceOfA;
C<2>::type anInstanceOfB
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;