I was wondering if anyone knows what the limits are on the conversion/typecast operator?
So, for example, I can have the following override operators:
class Test {
operator int() { return 0; };
operator int*() { return nullptr; };
}
For a regular function, I could also have a pointer to array type. E.g.
int (*MyFunc())[4] { return nullptr; };
However, I don’t know how to do the same for the conversion operator (or if it is even legal to do so). I have tried a few different variations and VS2010 and none work. (Such as:)
operator int (*())[4] { return nullptr; };
operator int(*)[4]() { return nullptr; };
I’m not sure if this is a limitation in VS2010 or if there is a general limit on the types that can be used in the conversion operator. I tried looking for the standard online with no luck. Does anyone know? Before anyone asks “why would you even want to do that”, it’s for auto-generated code. Although I don’t anticipate getting pointer to array input, I would like to be able to produce the code if it is legal in C++.
Yes, there are restrictions. The limitation you’ve hit with arrays is due to the language grammar. The grammar specification for a conversion operator (and kin) is as follows:
§12.3.2 conversion-function-id: operator conversion-type-id conversion-type-id: type-specifier-seq conversion-declarator[opt] conversion-declarator: ptr-operator conversion-declarator[opt] §7.1.6 type-specifier: trailing-type-specifier class-specifier enum-specifier trailing-type-specifier: simple-type-specifier elaborated-type-specifier typename-specifier cv-qualifier type-specifier-seq: type-specifier attribute-specifier-seq[opt] type-specifier type-specifier-seq trailing-type-specifier-seq: trailing-type-specifier attribute-specifier-seq[opt] trailing-type-specifier trailing-type-specifier-seqI leave it as an exercise for the reader to look at all those, but you can’t specify an array as the type directly. (It is only specified in declarations.) Luckily, though, a typedef-name is allowed (through the typename-specifier), and because a typedef is a kind of declaration, arrays work there:
Long story short, use a typedef and you can use whatever type you’d like.