我想在一个(非成员)函数上使用部分模板特化,并且我在语法上遇到了困难。我在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
部分特化,同时仍然允许多种 InType
。我尝试了各种方法,例如:
template <typename InType>
Grayscale ConvertPixel<InType, Grayscale>(InType source) {
return Grayscale(IntensityFromRGB(source.r, source.g, source.b));
}
但是(Microsoft VS 2008 C++)编译器拒绝了它。
我所尝试的是否可能?如果可能,正确的语法是什么?