c++ - Different casting operators used by different compilers -
the following c++ program compiles without warnings in compilers have tried (gcc 4.6.3, llvm 3.0, icc 13.1.1, solarisstudio 12.1/12.3):
struct cclass { template<class t> operator t() const { return 1; } operator int() const { return 2; } }; int main(void) { cclass x; return static_cast<char>(x); }
however, solarisstudio compilers return 2, solarisstudio (either version) returns 1, consider logical result.
using return x.operator char();
results in compilers returning 1.
obviously, since figuring out, have been using latter notation. however, know of compilers correct , why. (one think majority rules, still doesn't explain why.)
this question seems related questions here, here, , here, these "only" give solutions problems, no explanations (that able apply particular problem anyway).
note adding additional overloaded casting operator, operator float() const { return 3; }
results in compilers except solarisstudio complaining ambiguity.
the first (template) overload should picked.
paragraph 13.3.3/1 of c++11 standard specifies:
[...] viable function
f1
defined better function viable functionf2
if argumentsi
,icsi(f1)
not worse conversion sequenceicsi(f2)
, , then— argument
j
,icsj(f1)
better conversion sequenceicsj(f2)
, or, if not that,— the context initialization user-defined conversion (see 8.5, 13.3.1.5, , 13.3.1.6) and standard conversion sequence return type of
f1
destination type (i.e., type of entity being initialized) is better conversion sequence standard conversion sequence return type off2
destination type. [ example:struct { a(); operator int(); operator double(); } a; int = a; // a.operator int() followed no conversion // better a.operator double() followed // conversion int float x = a; // ambiguous: both possibilities require conversions, // , neither better other
—end example ] or, if not that,
—
f1
non-template function ,f2
function template specialization, or, if not that,[...]
as can see the, fact first conversion operator template becomes relevant when standard conversion sequence return type (char
, in case) destination type (char
, in case) not better standard conversion sequence return type of non-template overload (int
, in case) destination type (char
, in case).
however, standard conversion char
char
exact match, while standard conversion int
char
not. therefore, third item of § 13.3.3/1 not apply, , second item does.
this means the first (template) overload should picked.
Comments
Post a Comment