gpt4 book ai didi

C++:重新定义不同类型的模板类

转载 作者:行者123 更新时间:2023-11-30 05:15:58 25 4
gpt4 key购买 nike

我有两个(多个)枚举:

enum Choices1 : int
{
a,
b
};
enum Choices2 : int
{
c,
d
};

我希望能够将一个类型与这些枚举选择中的每一个相关联。如果我只有一组枚举 Choices1,我可以介绍:

template <Choices1 c>
struct choice_traits;

然后针对每个条目专门化它:

template <>
struct choice_traits<Choices1::a>
{
using MyType = float;
};

template <>
struct choice_traits<Choices1::b>
{
using MyType = double;

但我希望能够对多个枚举执行此操作,同时使用相同的关键字,例如:

template <>
struct choice_traits<Choices1::a>
{...};

template <>
struct choice_traits<Choices1::b>
{...};

template <>
struct choice_traits<Choices2::c>
{...};

template <>
struct choice_traits<Choices2::d>
{...};

这可能吗?如果是这样,非特例是什么?

如果没有,是否有任何替代方法将类型关联到每个 (Choice1::a,Choice1::b,Choice2::c,Choice2::d) 和可能有更多这样的枚举?

最佳答案

这不是一个很好的解决方案,但是......您可以为 Choiches1Choiches2 使用公共(public)基础 (int) 并定义非专用案例为

template <int>
struct choice_traits;

此时的问题是 Choiches1::a == Coiches2::cChoiches1::b == Choiches2::d 所以,如果你想定义类似的东西

template <>
struct choice_traits<Choices1::a>
{ using MyType = float; };

template <>
struct choice_traits<Choices1::b>
{ using MyType = double; };

template <>
struct choice_traits<Choices2::c>
{ using MyType = int; };

template <>
struct choice_traits<Choices2::d>
{ using MyType = long; };

您必须避免 Choiches1Choiches2 值之间的冲突。

如果您知道 Choiches1 值的数量,您可以使用更大的数字开始 Choiches2;例如,如果您确定 Choiches1 值少于 100,则可以按如下方式定义枚举

enum Choices1 : int
{ a = 0, b };

enum Choices2 : int
{ c = 100, d };

另一种解决方案可以为两个枚举使用偶数和奇数;像

enum Choices1 : int
{ a = 0, b = a+2 }; // add 2 for every next value

enum Choices2 : int
{ c = 1, d = c+2 }; // add 2 for every next value

下面是一个完整的例子

enum Choices1 : int
{ a = 0, b };

enum Choices2 : int
{ c = 100, d };

template <int>
struct choice_traits;

template <>
struct choice_traits<Choices1::a>
{ using MyType = float; };

template <>
struct choice_traits<Choices1::b>
{ using MyType = double; };

template <>
struct choice_traits<Choices2::c>
{ using MyType = int; };

template <>
struct choice_traits<Choices2::d>
{ using MyType = long; };

int main()
{
choice_traits<a>::MyType fl { 1.1f };
choice_traits<b>::MyType db { 2.2 };
choice_traits<c>::MyType in { 3 };
choice_traits<d>::MyType ln { 4L };
}

关于C++:重新定义不同类型的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42878565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com