c – 我可以对(非成员)函数使用部分模板特化吗?
发布时间:2020-12-16 10:39:09 所属栏目:百科 来源:网络整理
导读:我正在尝试在(非成员)函数上使用部分模板特化,而我正在绊倒语法.我已经在StackOverflow中搜索了其他部分模板特化问题,但这些问题涉及类或成员函数模板的部分特化. 作为一个起点,我有: struct RGBA { RGBA(uint8 red,uint8 green,uint8 blue,uint8 alpha = 2
我正在尝试在(非成员)函数上使用部分模板特化,而我正在绊倒语法.我已经在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 function template<class A,class B> A Convert(B source) { return typename Functor<A,B>::convert(source); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |