gpt4 book ai didi

c++ - 组类模板特化

转载 作者:可可西里 更新时间:2023-11-01 14:56:52 24 4
gpt4 key购买 nike

是否有一种技术/最佳风格来对特定类型的类模板特化进行分组?

举个例子:假设我有一个类模板Foo,我需要将它专门用于排版

A = { Line, Ray }

还有另一种排版方式B

B = { Linestring, Curve }

到目前为止我在做什么:(该技术还针对函数提供了 here)

#include <iostream>
#include <type_traits>
using namespace std;

// 1st group
struct Line {};
struct Ray {};
// 2nd group
struct Curve {};
struct Linestring {};

template<typename T, typename Groupper=void>
struct Foo
{ enum { val = 0 }; };

// specialization for the 1st group
template<typename T>
struct Foo<T, typename enable_if<
is_same<T, Line>::value ||
is_same<T, Ray>::value
>::type>
{
enum { val = 1 };
};

// specialization for the 2nd group
template<typename T>
struct Foo<T, typename enable_if<
is_same<T, Curve>::value ||
is_same<T, Linestring>::value
>::type>
{
enum { val = 2 };
};

int main()
{
cout << Foo<Line>::val << endl;
cout << Foo<Curve>::val << endl;
return 0;
}

额外的辅助结构 enable_for 会缩短代码(并允许直接编写接受的类型)。还有其他建议,更正吗?这不应该减少工作量吗?

最佳答案

您也可以使用您自己的特征而不使用 enable_if:

// Traits

template <class T>
struct group_number : std::integral_constant<int, 0> {};

template <>
struct group_number<Line> : std::integral_constant<int, 1> {};

template <>
struct group_number<Ray> : std::integral_constant<int, 1> {};

template <>
struct group_number<Linestring> : std::integral_constant<int, 2> {};

template <>
struct group_number<Curve> : std::integral_constant<int, 2> {};


// Foo

template <class T, int Group = group_number<T>::value>
class Foo
{
//::: whatever
};

template <class T>
class Foo<T, 1>
{
//::: whatever for group 1
};

template <class T>
class Foo<T, 2>
{
//::: whatever for group 2
};

这样做的好处是可以自动确保每种类型最多属于一个组。

关于c++ - 组类模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24628099/

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