c++ - 模板特化问题

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

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

我有一个 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;
};

这对我来说非常有效,直到我满足了固定点的需求。最大值有点不同,我不知道如何创建类型规范特化来隔离它。我唯一的解决方法是消除和创建 float 和 double 的特化过程,并假设一般情况是 fixed-pt。但是必须有更好的方法来做到这一点。这是我想对不正确的代码执行的操作:

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?
它适用于一般情况,只是无法将其隔离。

最佳答案

也许我遗漏了一些更复杂的问题,但是有什么理由不能只是部分特化 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;
};

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

相关文章:

c++ - 为什么无法通过将数据传递给某个函数来在全局范围内初始化数据?

c++ - 无法从命令行 VS2017 为 C++ 运行 msbuild

c++ - 模板参数中的 const

scala - 在 play framework 2.1.1 中更改模板中的文本语言

visual-studio - Visual Studio 解决方案 - 如何确保共享项目属性?

javascript - 对所有页面使用相同的 Handlebars 模板

c++ - 是否可以根据反汇编推断source中哪一行有问题?

c++ - 如何将编译时元数据/行为添加到特定函数

c++ - 为什么这段代码不能使用 MS 编译器编译?

visual-studio - 设计时在 Visual Studio .net 中画一条线