Note that there are some explanatory texts on larger screens.

plurals
  1. POOverloading conversion operator template
    primarykey
    data
    text
    <p>Consider the following simple example</p> <pre><code>struct C { template &lt;typename T&gt; operator T () {return 0.5;} operator int () {return 1;} operator bool () {return false;} }; int main () { C c; double x = c; std::cout &lt;&lt; x &lt;&lt; std::endl; } </code></pre> <p>When compiled with Clang, it gives the following error</p> <pre><code>test.cpp:11:12: error: conversion from 'C' to 'double' is ambiguous double x = c; ^ ~ test.cpp:4:5: note: candidate function operator int () {return 1;} ^ test.cpp:5:5: note: candidate function operator bool () {return false;} ^ test.cpp:3:27: note: candidate function [with T = double] template &lt;typename T&gt; operator T () {return 0.5;} ^ 1 error generated. </code></pre> <p>Other compilers generate similar errors, e.g., GCC and Intel iclc</p> <p>If I remove <code>operator int</code> and <code>operator bool</code>. It compiles fine and work as expected. If only remove one of them, that is keep the template operator and say <code>operator int</code>, then the non-template version is always chosen.</p> <p>My understanding is that only when the template and non-template overloaded functions are equal in the sense that they are both perfect match or both require the same conversion sequence, the non-template version will be preferred. However in this case, it appears that the compiler does not see the operator template as a perfect match. And when both the <code>bool</code> and <code>int</code> overloading are present, then naturally it considers they are ambiguous.</p> <p>In summary, my question is that why the operator template is not considered a perfect match in this case?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload