简体   繁体   English

我可以在编译时使用常数来选择一个类,可能使用模板吗?

[英]May I use a constant number to choose a class at compile time, possibly using templates?

Let's say I have a constant value (possibly of some enum type). 假设我有一个常量值(可能是一些枚举类型)。 Let's say I have many classes A, B, D, etc. 假设我有很多A,B,D等课程。

Can I have something like this? 我能有这样的东西吗?

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

So, is it possible to select a class based on a constant number at compile time? 那么,是否可以在编译时根据常数选择一个类?

The general problem is that I am trying to select a functor based on a table, in which the index is an enum. 一般的问题是我试图根据表选择一个仿函数,其中索引是一个枚举。 I would like to avoid polymorfism if possible. 如果可能的话,我想避免多态性。

Edit: For this project I cannot use C++11, thanks anyway to who answered in that context, very interesting to know anyway. 编辑:对于这个项目,我不能使用C ++ 11,无论如何,感谢谁在那个环境中回答,无论如何都知道非常有趣。
Edit 2: In general I can have more than 2 target classes, I have edited my question 编辑2:一般来说,我可以有两个以上的目标类,我编辑了我的问题

This isn't the only way to do this, but I hope acceptable for your purposes: 这不是唯一的方法,但我希望你的目的可以接受:

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;

Update: To do the same without C++11 features, you should make C a class with a typedef member type equal to the corresponding type alias above: 更新:要在没有C ++ 11功能的情况下执行相同操作,您应该使C类成为类型与上面相应类型别名相同的typedef成员:

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

// ...
C<1>::type anInstanceOfA;
C<2>::type anInstanceOfB

Using the LSP and plain C++98: 使用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;

Since public inheritance in C++ satisfies the IS-A rule, anInstanceOfA both IS-A C<1> object and IS_AN A object. 由于C ++中的公共继承满足IS-A规则,因此anInstanceOfA既是IS-A C<1>对象又是IS_AN A对象。

This is a fairly simple metafunction: 这是一个相当简单的元函数:

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

You would use this as C<1>::type foo; 你可以使用它作为C<1>::type foo; .

If your compiler supports C++11 template aliases, you can simplify to: 如果您的编译器支持C ++ 11模板别名,则可以简化为:

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

and have your preferred C<1> foo; 并拥有你喜欢的C<1> foo; syntax. 句法。

In pure C++03, implement std::conditional as: 在纯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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM