我可以为(非成员)函数使用部分模板专门化吗? [英] Can I use partial template specialization for a (non-member) function?
问题描述
我试图对(非成员)函数使用部分模板专门化,我跳过了语法。我已经搜索StackOverflow的其他部分模板专门化问题,但那些处理类或成员函数模板的部分专门化。
I'm trying to use partial template specialization on a (non-member) function, and I'm tripping up on the syntax. I've searched StackOverflow for other partial template specialization questions, but those deal with partial specialization of a class or member function template.
对于一个起点,我有: / p>
For a starting point, I have:
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到灰度转换功能像这样: p>
I can do a complete specialization of ConvertPixel to make an RGBA to Grayscale conversion function like this:
template <>
Grayscale ConvertPixel<RGBA, Grayscale>(RGBA source) {
return Grayscale(IntensityFromRGB(source.r, source.g, source.b));
}
我可以想象有更多的像素类型提供红,绿,蓝,但也许以不同的格式,所以我真正想做的是通过指定 Grayscale
OutType
并仍然允许各种 InType
。我尝试了这样的各种方法:
I'll conceivably have more pixel types that offer red, green, and blue, but perhaps in a different format, so what I'd really like to do is a partial specialization by specifying Grayscale
for OutType
and still allow for a variety of InType
s. I've tried a variety of approaches like this:
template <typename InType>
Grayscale ConvertPixel<InType, Grayscale>(InType source) {
return Grayscale(IntensityFromRGB(source.r, source.g, source.b));
}
但是Microsoft VS 2008 C ++编译器拒绝它。
But the (Microsoft VS 2008 C++) compiler rejects it.
我试图可能吗?
推荐答案
可以使用类别partitial specialization:
It is possible using 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.g, source.b));
}
};
// Common function
template<class A, class B>
A Convert(B source) {
return typename Functor<A,B>::convert(source);
}
这篇关于我可以为(非成员)函数使用部分模板专门化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!