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

Adr*_*thy 4 c++ templates partial-specialization

我正在尝试在(非成员)函数上使用部分模板特化,而我正在绊倒语法.我已经在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);
Run Code Online (Sandbox Code Playgroud)

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

template <>
Grayscale ConvertPixel<RGBA, Grayscale>(RGBA source) {
    return Grayscale(IntensityFromRGB(source.r, source.g, source.b));
}
Run Code Online (Sandbox Code Playgroud)

我可以想象有提供红色,绿色和蓝色更像素类型,但也许在不同的格式,所以我真的很想做的是通过指定一个局部特殊化GrayscaleOutType,仍然允许多种InType秒.我尝试过各种各样的方法:

template <typename InType>
Grayscale ConvertPixel<InType, Grayscale>(InType source) {
    return Grayscale(IntensityFromRGB(source.r, source.g, source.b));
}
Run Code Online (Sandbox Code Playgroud)

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

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

Ste*_*sop 8

C++不允许对函数模板进行部分特化.

它甚至不允许成员函数模板的部分特化.当您定义一个函数时,该函数是类模板的部分特化的一部分,这可能看起来有点像您已经部分专门化了成员函数.但你还没有.

Herb Sutter讨论了部分专业化


Ale*_*tov 5

可以使用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);
}
Run Code Online (Sandbox Code Playgroud)