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

标签 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

那么,是否可以在编译时根据一个常量来选择类呢?

一般的问题是我试图根据表选择一个仿函数,其中索引是一个枚举。如果可能,我想避免多态性。

编辑:对于这个项目,我不能使用 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/

相关文章:

c++ - 文件是否保证在 ofstream::close() 返回后可以立即打开以供读取?

c++模板化为特定类型而不使用传统的模板特化

c++ - 二维 vector 大小的 Visual Studio 2015 断点条件

Spring Freemarker配置,未找到模板

json - 通过 CLI 进行 Azure ARM 模板部署失败,并出现 .ps1 脚本扩展错误

c++ - 使用 fstream 从文本文件中读取数据

c++ - 如何修复 "Member is ambiguous"错误?

c++ - 为什么我无法使用 C++11 基于范围的 for 循环迭代 vector ?

c++ - Qt中应该使用哪种内存管理方式?

c++ - 最低公共(public)祖先优化