Can I use a private template specialization for a function (not a member)?

I am trying to use a partial specialization of a template for a function (not a member), and I can disconnect from the syntax. I was looking for StackOverflow for other questions on partial specialization of templates, but this concerns partial specialization of a template of a class or member function.

For the 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);

I can do the full ConvertPixel specialization to make the RGBA to Grayscale conversion function as follows:

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

, , , , , , , , Grayscale OutType InType s. :

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

(Microsoft VS 2008 ++) .

? , ?

+3
3

partitial :

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);
}
+5

++ .

-. , , , -. .

Herb Sutter

+7

- , , -. , , , , ( -) , - , .

+2

Source: https://habr.com/ru/post/1726590/


All Articles