【问题标题】:Template specialization problem模板特化问题
【发布时间】:2009-11-02 20:20:19
【问题描述】:

我非常努力地完成这项工作,但我没有运气。我确信有一个解决方法,但我还没有遇到它。好吧,让我们看看我是否可以简单地描述问题和需求:

我有一个 RGB 模板类,它可以将类型名作为其模板参数之一。它获取类型名并将其发送到另一个模板,该模板创建其基本类型的分类。例如:

struct float_type {};
struct bit_type {};
struct fixed_pt_type {};

template <typename T> struct type_specification { typedef float_type type; };

template <> struct type_specification<char>      { typedef bit_type type; };
template <> struct type_specification<short>     { typedef bit_type type; };
template <> struct type_specification<int>       { typedef bit_type type; };
template <> struct type_specification<long>      { typedef bit_type type; };
template <> struct type_specification<long long> { typedef bit_type type; };

然后,我有一个模板,可以根据每个 RGB 值的位数计算最大值:

template <int Bits, typename T> struct Max_Values { enum { MaxValue = (1 << Bits) - 1; }; };
template <int Bits> struct MaxValues<float_type>  { enum { MaxValue = 1.0; }; };

然后在实际的RGB模板类中,我有:

enum
{
     RMax = Max_Values<RBits, type_specification<T>::type>::MaxValue;
     GMax = Max_Values<GBits, type_specification<T>::type>::MaxValue;
     BMax = Max_Values<BBits, type_specification<T>::type>::MaxValue;
};

这对我来说非常有效,直到我满足了固定点的需求。最大值有点不同,我不知道如何创建一个类型规范专业化来隔离它。我唯一的解决方法是消除和创建浮点和双精度的专门化过程,并假设一般情况是固定点。但必须有更好的方法来做到这一点。这是我想要对错误代码执行的操作:

template <> struct type_specification<fixed_pt_t> { typedef fixed_pt_type type; };

不过,fixed-pt-t 是一个模板类,看起来像:

template <int N, typename T, template <class> class Policy> struct fixed_pt_t

所以编译器不喜欢没有模板参数的特化。
有没有办法专门化我的类型规范类以使用 fixed-pt-t?
它适用于一般情况,只是无法隔离它。

【问题讨论】:

    标签: c++ visual-studio-2008 templates metaprogramming specialization


    【解决方案1】:

    也许我遗漏了一些更大的复杂性,但有什么理由不能只对type_specification 模板进行部分专业化?

    类似这样的:

    template <int N, typename T, template <class> class Policy>
    struct type_specification< fixed_pt_t<N, T, Policy> >
    {
        typedef fixed_pt_type type;
    };
    

    【讨论】:

    • 你知道,我确实试过了,但它从来没有运行过代码。我假设因为 max-values::type>::value 使用单个类型名 T(在这种情况下为固定-pt-t)运行,所以它使用了简单的专业化。
    • 哦,嘘。你知道吗。它确实奏效了。我只是没有正确设置最大值的方程,所以我认为它没有运行代码。这几天我一直在用头撞墙!谢谢,您的解决方案效果很好!
    • 好的,那没关系,我只是敲了一个快速测试应用程序来检查我的理智。我只想指出,您在问题的很多地方都缺少关键字struct。也许您想对其进行编辑以使其更具可编译性。
    • 是的,我在上面添加了所有结构关键字,因此它更易于编译。我等不及模板元编程更容易调试了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    相关资源
    最近更新 更多