小组课程模板专长 [英] Group class template specializations

查看:53
本文介绍了小组课程模板专长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在某种技巧/最佳风格来对某些类型的类模板专业进行分组?

一个示例:可以说我有一个类模板 Foo ,我需要将其专门用于排版

An example : Lets say I have a class template Foo and I need to have it specialized the same for the typeset

A = { Line, Ray }

并以另一种方式输入排版B

and in another way for the typeset B

B = { Linestring, Curve }






我到目前为止正在做的事情:(该技术还提供了此处(有关函数))

#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 将缩短代码(并允许直接编写接受的类型)。还有其他建议,更正吗?

An extra helper struct enable_for would shorten the code (and allow to write the accepted types directly). Any other suggestions, corrections? Shouldn't this involve less effort?

推荐答案

您也可以根据自己的特征进行操作,而无需 enable_if

You can also do this with your own traits and without 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
};

优点是可以自动确保每种类型最多包含一组。

This has the advantage of automatically ensuring that each type is in at most one group.

这篇关于小组课程模板专长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆