c – 我可以对(非成员)函数使用部分模板特化吗?

c – 我可以对(非成员)函数使用部分模板特化吗?,第1张

概述我正在尝试在(非成员)函数上使用部分模板特化,而我正在绊倒语法.我已经在StackOverflow中搜索了其他部分模板特化问题,但这些问题涉及类或成员函数模板的部分特化. 作为一个起点,我有: struct RGBA { RGBA(uint8 red, uint8 green, uint8 blue, uint8 alpha = 255) : r(red), g(green 我正在尝试在(非成员)函数上使用部分模板特化,而我正在绊倒语法.我已经在StackOverflow中搜索了其他部分模板特化问题,但这些问题涉及类或成员函数模板的部分特化.

作为一个起点,我有:

struct RGBA {    RGBA(uint8 red,uint8 green,uint8 blue,uint8 Alpha = 255) :        r(red),g(green),b(blue),a(Alpha)    {}    uint8 r,g,b,a;};struct Grayscale {    Grayscale(uint8 intensity) : value(intensity) {}    uint8 value;};inline uint8 IntensityFromrGB(uint8 r,uint8 g,uint8 b) {    return static_cast<uint8>(0.30*r + 0.59*g + 0.11*b);}// Generic pixel conversion.  Must specialize this template for specific// conversions.template <typename InType,typename OutType>OutType ConvertPixel(InType source);

我可以完全专门化ConvertPixel来制作RGBA到灰度转换函数,如下所示:

template <>Grayscale ConvertPixel<RGBA,Grayscale>(RGBA source) {    return Grayscale(IntensityFromrGB(source.r,source.g,source.b));}

我可以想象有更多像素类型提供红色,绿色和蓝色,但可能采用不同的格式,所以我真正想做的是通过为OutType指定Grayscale并且仍然允许各种InTypes来实现部分特化.我尝试过各种各样的方法:

template <typename InType>Grayscale ConvertPixel<InType,Grayscale>(InType source) {    return Grayscale(IntensityFromrGB(source.r,source.b));}

但是(Microsoft VS 2008 C)编译器拒绝它.

我正在尝试的是什么?如果是这样,那么正确的语法是什么?

解决方法 可以使用class partitial specialization:

template<class A,class B>struct Functor {    static A convert(B source);};template<class B>struct Functor<GrayScale,B> {    static GrayScale convert(B source) {         return Grayscale(IntensityFromrGB(source.r,source.b));    }};// Common functiontemplate<class A,class B>A Convert(B source) {   return typename Functor<A,B>::convert(source);}
总结

以上是内存溢出为你收集整理的c – 我可以对(非成员)函数使用部分模板特化吗?全部内容,希望文章能够帮你解决c – 我可以对(非成员)函数使用部分模板特化吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1221757.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存