6

假设我有一个常量值(可能是某种枚举类型)。假设我有很多 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 个以上的目标类,我已经编辑了我的问题

4

3 回答 3

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;

更新:要在没有 C++11 特性的情况下做同样的事情,您应该创建C一个typedef成员类型等于上面相应类型别名的类:

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

// ...
C<1>::type anInstanceOfA;
C<2>::type anInstanceOfB
于 2013-07-30T14:55:12.003 回答
9

使用 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++ 中的公共继承满足 IS-A 规则,anInstanceOfA因此 IS-AC<1>对象和 IS_ANA对象都满足。

于 2013-07-30T15:20:55.250 回答
4

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

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

您可以将其用作C<1>::type foo;.

如果您的编译器支持 C++11 模板别名,您可以简化为:

template <int N>
using C = typename std::conditional<N == 1,A,B>::type;

并拥有您喜欢的C<1> foo;语法。

在纯 C++03 中,实现std::conditional为:

template <bool, typename A, typename>
struct conditional {
  typedef A type;
};

template <typename A, typename B>
struct conditional<false, A, B> {
  typedef B type;
};
于 2013-07-30T14:54:00.460 回答