0

So I have a templated Image class, for which I am trying to set up inline color-conversions. This is a simplification of the code that is vexing me:

template <typename Color = colors::RGB>
class Image {

    /// ...

    template <typename DestColor>
    operator Image<DestColor>() {
        /// when assigning with a different colorspace:
        /// ... do the color conversion
        /// ... and return a fresh Image<DestColor>
    }

    template <>
    operator Image<Color>() {
        /// when assigning with the same colorspace:
        return *this;
    }

};

… the problem is that the template specialization that follows the templated conversion operator can’t be defined at the class level (according to the errors I am getting).

I get that one needs to specify the specialization out-of-line, but I can’t for the life of me figure out the syntax. How should I declare that specialization?

fish2000
  • 4,289
  • 2
  • 37
  • 76
  • 1
    If I am not mistaken, you can't declare a full template class specialization inside a class, adding a dummy class template parameter default to void might solve the problem if it doesn't bother you. – Caninonos Aug 20 '15 at 22:15
  • Aha, what would that look like, if I may ask? – fish2000 Aug 20 '15 at 22:15
  • 2
    It would look like [that](http://ideone.com/Udekt9) (Edit: you can also make it private and declare a public alias/template derived struct to hide that dummy parameter if it bothers you and you don't have any better method) – Caninonos Aug 20 '15 at 22:17
  • Interesting, if that works with the `operator` declarations it might be the solution. Do you happen to have an example of the private alias syntax and method for hiding the parameter? – fish2000 Aug 20 '15 at 22:23
  • Sure, I've edited the previous live example to include them. – Caninonos Aug 20 '15 at 22:27
  • Nice! I will try these out in practice (I am using C++14 so `using` templates are fine), thanks! – fish2000 Aug 20 '15 at 22:31
  • 1
    I reread this question, and noticed I misread conversion operators for inner class declarations, in that case, just overloading the conversion operator is perfectly fine [example](http://ideone.com/MChQq1) (of course, you can apply the aforementioned trick, but I had inner classes in mind rather than methods) – Caninonos Aug 20 '15 at 22:49

1 Answers1

4

Just remove the specialization. Your conversion function will never be called anyway if DestColor is the same as Color. [class.conv.fct]/p1:

A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • Oh man – I feel kind of dumb now that you have pointed that out; but yeah thanks! That certainly simplifies things. – fish2000 Aug 21 '15 at 04:12