Why is implicit conversion not ambiguous for non-primitive types?Can you use keyword explicit to prevent automatic conversion of method parameters?Why const for implicit conversion?Implicit conversion when overloading operators for template classesTemplate Constructor for Primitives, avoiding AmbiguityTemplate Type Deduction with Lambdasimplicit conversions from and to class typesConversion is ambiguous. Standard implicit conversion could not choose cast operatorGet type of implicit conversionImplicit conversion of stream to boolC++17: explicit conversion function vs explicit constructor + implicit conversions - have the rules changed?

python displays `n` instead of breaking a line

is this saw blade faulty?

Reasons for having MCU pin-states default to pull-up/down out of reset

Center page as a whole without centering each element individually

Control width of columns in a tabular environment

Why didn’t Eve recognize the little cockroach as a living organism?

Weird lines in Microsoft Word

Is there a page on which I can view all Sitecore jobs running?

Should a narrator ever describe things based on a character's view instead of facts?

Is there any common country to visit for persons holding UK and Schengen visas?

When is the exact date for EOL of Ubuntu 14.04 LTS?

A seasonal riddle

Comic-book: Kids find a dead female superhero in the woods

categorizing a variable turns it from insignificant to significant

How do you justify more code being written by following clean code practices?

Mortal danger in mid-grade literature

Hashing password to increase entropy

Travelling in US for more than 90 days

Can a Knock spell open the door to Mordenkainen's Magnificent Mansion?

New Order #2: Turn My Way

How to test the sharpness of a knife?

What is this high flying aircraft over Pennsylvania?

Checking @@ROWCOUNT failing

How are passwords stolen from companies if they only store hashes?



Why is implicit conversion not ambiguous for non-primitive types?


Can you use keyword explicit to prevent automatic conversion of method parameters?Why const for implicit conversion?Implicit conversion when overloading operators for template classesTemplate Constructor for Primitives, avoiding AmbiguityTemplate Type Deduction with Lambdasimplicit conversions from and to class typesConversion is ambiguous. Standard implicit conversion could not choose cast operatorGet type of implicit conversionImplicit conversion of stream to boolC++17: explicit conversion function vs explicit constructor + implicit conversions - have the rules changed?













7















Given a simple class template with multiple implicit conversion functions (non-explicit constructor and conversion operator), as in the following example:



template<class T>
class Foo

private:
T m_value;

public:
Foo();

Foo(const T& value):
m_value(value)



operator T() const
return m_value;


bool operator==(const Foo<T>& other) const
return m_value == other.m_value;

;

struct Bar

bool m;

bool operator==(const Bar& other) const
return false;

;

int main(int argc, char *argv[])

Foo<bool> a (true);
bool b = false;
if(a == b)
// This is ambiguous


Foo<int> c (1);
int d = 2;
if(c == d)
// This is ambiguous


Foo<Bar> e (Bartrue);
Bar f = false;
if(e == f)
// This is not ambiguous. Why?




The comparison operators involving primitive types (bool, int) are ambiguous, as expected - the compiler does not know whether it should use the conversion operator to convert the left-hand template class instance to a primitive type or use the conversion constructor to convert the right-hand primitive type to the expected class template instance.



However, the last comparison, involving a simple struct, is not ambiguous. Why? Which conversion function will be used?



Tested with compiler msvc 15.9.7.










share|improve this question






















  • The explicit keyword is a nice thing. You should research it.

    – Jesper Juhl
    2 hours ago











  • e == f will be ambiguous in C++20, for what its worth.

    – Barry
    1 hour ago















7















Given a simple class template with multiple implicit conversion functions (non-explicit constructor and conversion operator), as in the following example:



template<class T>
class Foo

private:
T m_value;

public:
Foo();

Foo(const T& value):
m_value(value)



operator T() const
return m_value;


bool operator==(const Foo<T>& other) const
return m_value == other.m_value;

;

struct Bar

bool m;

bool operator==(const Bar& other) const
return false;

;

int main(int argc, char *argv[])

Foo<bool> a (true);
bool b = false;
if(a == b)
// This is ambiguous


Foo<int> c (1);
int d = 2;
if(c == d)
// This is ambiguous


Foo<Bar> e (Bartrue);
Bar f = false;
if(e == f)
// This is not ambiguous. Why?




The comparison operators involving primitive types (bool, int) are ambiguous, as expected - the compiler does not know whether it should use the conversion operator to convert the left-hand template class instance to a primitive type or use the conversion constructor to convert the right-hand primitive type to the expected class template instance.



However, the last comparison, involving a simple struct, is not ambiguous. Why? Which conversion function will be used?



Tested with compiler msvc 15.9.7.










share|improve this question






















  • The explicit keyword is a nice thing. You should research it.

    – Jesper Juhl
    2 hours ago











  • e == f will be ambiguous in C++20, for what its worth.

    – Barry
    1 hour ago













7












7








7








Given a simple class template with multiple implicit conversion functions (non-explicit constructor and conversion operator), as in the following example:



template<class T>
class Foo

private:
T m_value;

public:
Foo();

Foo(const T& value):
m_value(value)



operator T() const
return m_value;


bool operator==(const Foo<T>& other) const
return m_value == other.m_value;

;

struct Bar

bool m;

bool operator==(const Bar& other) const
return false;

;

int main(int argc, char *argv[])

Foo<bool> a (true);
bool b = false;
if(a == b)
// This is ambiguous


Foo<int> c (1);
int d = 2;
if(c == d)
// This is ambiguous


Foo<Bar> e (Bartrue);
Bar f = false;
if(e == f)
// This is not ambiguous. Why?




The comparison operators involving primitive types (bool, int) are ambiguous, as expected - the compiler does not know whether it should use the conversion operator to convert the left-hand template class instance to a primitive type or use the conversion constructor to convert the right-hand primitive type to the expected class template instance.



However, the last comparison, involving a simple struct, is not ambiguous. Why? Which conversion function will be used?



Tested with compiler msvc 15.9.7.










share|improve this question














Given a simple class template with multiple implicit conversion functions (non-explicit constructor and conversion operator), as in the following example:



template<class T>
class Foo

private:
T m_value;

public:
Foo();

Foo(const T& value):
m_value(value)



operator T() const
return m_value;


bool operator==(const Foo<T>& other) const
return m_value == other.m_value;

;

struct Bar

bool m;

bool operator==(const Bar& other) const
return false;

;

int main(int argc, char *argv[])

Foo<bool> a (true);
bool b = false;
if(a == b)
// This is ambiguous


Foo<int> c (1);
int d = 2;
if(c == d)
// This is ambiguous


Foo<Bar> e (Bartrue);
Bar f = false;
if(e == f)
// This is not ambiguous. Why?




The comparison operators involving primitive types (bool, int) are ambiguous, as expected - the compiler does not know whether it should use the conversion operator to convert the left-hand template class instance to a primitive type or use the conversion constructor to convert the right-hand primitive type to the expected class template instance.



However, the last comparison, involving a simple struct, is not ambiguous. Why? Which conversion function will be used?



Tested with compiler msvc 15.9.7.







c++ templates c++17 implicit-conversion ambiguous






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 hours ago









CybranCybran

1,047818




1,047818












  • The explicit keyword is a nice thing. You should research it.

    – Jesper Juhl
    2 hours ago











  • e == f will be ambiguous in C++20, for what its worth.

    – Barry
    1 hour ago

















  • The explicit keyword is a nice thing. You should research it.

    – Jesper Juhl
    2 hours ago











  • e == f will be ambiguous in C++20, for what its worth.

    – Barry
    1 hour ago
















The explicit keyword is a nice thing. You should research it.

– Jesper Juhl
2 hours ago





The explicit keyword is a nice thing. You should research it.

– Jesper Juhl
2 hours ago













e == f will be ambiguous in C++20, for what its worth.

– Barry
1 hour ago





e == f will be ambiguous in C++20, for what its worth.

– Barry
1 hour ago












2 Answers
2






active

oldest

votes


















10














According to [over.binary]/1




Thus, for any binary operator @, x@y can be interpreted
as either x.operator@(y) or operator@(x,y).




According to this rule, in the case of e == f, the compiler can only interpret it as e.operator==(f), not as f.operator==(e). So there is no ambiguity; the operator== you defined as a member of Bar is simply not a candidate for overload resolution.



In the case of a == b and c == d, the built-in candidate operator==(int, int) (see [over.built]/13) competes with the operator== defined as a member of Foo<T>.






share|improve this answer






























    2














    Operator overloads implemented as member functions don't allow for implicit conversion of their left hand side operand, which is the object on which they are called. It always helps to write down the explicit form of the operator overload to see what that means:



    Foo<Bar> e (Bartrue);
    Bar f = false;

    // Pretty explicit: call the member function Foo<Bar>::operator==
    if(e.operator ==(f)) /* ... */


    This can't be confused with the comparison operator in Bar, because it would require an implicit conversion of the left hand side operand, which is impossible. You can trigger an ambiguity similar to the ones you see with the builtin types when you define Bar and its comparison operator like this:



    struct Bar bool m; ;

    // A free function allows conversion, this will be ambigious:
    bool operator==(const Bar&, const Bar&)

    return false;



    This is nicely demonstrated and explained in Item 24, Scott Meyers, Effective C++.






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55249017%2fwhy-is-implicit-conversion-not-ambiguous-for-non-primitive-types%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      10














      According to [over.binary]/1




      Thus, for any binary operator @, x@y can be interpreted
      as either x.operator@(y) or operator@(x,y).




      According to this rule, in the case of e == f, the compiler can only interpret it as e.operator==(f), not as f.operator==(e). So there is no ambiguity; the operator== you defined as a member of Bar is simply not a candidate for overload resolution.



      In the case of a == b and c == d, the built-in candidate operator==(int, int) (see [over.built]/13) competes with the operator== defined as a member of Foo<T>.






      share|improve this answer



























        10














        According to [over.binary]/1




        Thus, for any binary operator @, x@y can be interpreted
        as either x.operator@(y) or operator@(x,y).




        According to this rule, in the case of e == f, the compiler can only interpret it as e.operator==(f), not as f.operator==(e). So there is no ambiguity; the operator== you defined as a member of Bar is simply not a candidate for overload resolution.



        In the case of a == b and c == d, the built-in candidate operator==(int, int) (see [over.built]/13) competes with the operator== defined as a member of Foo<T>.






        share|improve this answer

























          10












          10








          10







          According to [over.binary]/1




          Thus, for any binary operator @, x@y can be interpreted
          as either x.operator@(y) or operator@(x,y).




          According to this rule, in the case of e == f, the compiler can only interpret it as e.operator==(f), not as f.operator==(e). So there is no ambiguity; the operator== you defined as a member of Bar is simply not a candidate for overload resolution.



          In the case of a == b and c == d, the built-in candidate operator==(int, int) (see [over.built]/13) competes with the operator== defined as a member of Foo<T>.






          share|improve this answer













          According to [over.binary]/1




          Thus, for any binary operator @, x@y can be interpreted
          as either x.operator@(y) or operator@(x,y).




          According to this rule, in the case of e == f, the compiler can only interpret it as e.operator==(f), not as f.operator==(e). So there is no ambiguity; the operator== you defined as a member of Bar is simply not a candidate for overload resolution.



          In the case of a == b and c == d, the built-in candidate operator==(int, int) (see [over.built]/13) competes with the operator== defined as a member of Foo<T>.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 2 hours ago









          BrianBrian

          65.6k797186




          65.6k797186























              2














              Operator overloads implemented as member functions don't allow for implicit conversion of their left hand side operand, which is the object on which they are called. It always helps to write down the explicit form of the operator overload to see what that means:



              Foo<Bar> e (Bartrue);
              Bar f = false;

              // Pretty explicit: call the member function Foo<Bar>::operator==
              if(e.operator ==(f)) /* ... */


              This can't be confused with the comparison operator in Bar, because it would require an implicit conversion of the left hand side operand, which is impossible. You can trigger an ambiguity similar to the ones you see with the builtin types when you define Bar and its comparison operator like this:



              struct Bar bool m; ;

              // A free function allows conversion, this will be ambigious:
              bool operator==(const Bar&, const Bar&)

              return false;



              This is nicely demonstrated and explained in Item 24, Scott Meyers, Effective C++.






              share|improve this answer





























                2














                Operator overloads implemented as member functions don't allow for implicit conversion of their left hand side operand, which is the object on which they are called. It always helps to write down the explicit form of the operator overload to see what that means:



                Foo<Bar> e (Bartrue);
                Bar f = false;

                // Pretty explicit: call the member function Foo<Bar>::operator==
                if(e.operator ==(f)) /* ... */


                This can't be confused with the comparison operator in Bar, because it would require an implicit conversion of the left hand side operand, which is impossible. You can trigger an ambiguity similar to the ones you see with the builtin types when you define Bar and its comparison operator like this:



                struct Bar bool m; ;

                // A free function allows conversion, this will be ambigious:
                bool operator==(const Bar&, const Bar&)

                return false;



                This is nicely demonstrated and explained in Item 24, Scott Meyers, Effective C++.






                share|improve this answer



























                  2












                  2








                  2







                  Operator overloads implemented as member functions don't allow for implicit conversion of their left hand side operand, which is the object on which they are called. It always helps to write down the explicit form of the operator overload to see what that means:



                  Foo<Bar> e (Bartrue);
                  Bar f = false;

                  // Pretty explicit: call the member function Foo<Bar>::operator==
                  if(e.operator ==(f)) /* ... */


                  This can't be confused with the comparison operator in Bar, because it would require an implicit conversion of the left hand side operand, which is impossible. You can trigger an ambiguity similar to the ones you see with the builtin types when you define Bar and its comparison operator like this:



                  struct Bar bool m; ;

                  // A free function allows conversion, this will be ambigious:
                  bool operator==(const Bar&, const Bar&)

                  return false;



                  This is nicely demonstrated and explained in Item 24, Scott Meyers, Effective C++.






                  share|improve this answer















                  Operator overloads implemented as member functions don't allow for implicit conversion of their left hand side operand, which is the object on which they are called. It always helps to write down the explicit form of the operator overload to see what that means:



                  Foo<Bar> e (Bartrue);
                  Bar f = false;

                  // Pretty explicit: call the member function Foo<Bar>::operator==
                  if(e.operator ==(f)) /* ... */


                  This can't be confused with the comparison operator in Bar, because it would require an implicit conversion of the left hand side operand, which is impossible. You can trigger an ambiguity similar to the ones you see with the builtin types when you define Bar and its comparison operator like this:



                  struct Bar bool m; ;

                  // A free function allows conversion, this will be ambigious:
                  bool operator==(const Bar&, const Bar&)

                  return false;



                  This is nicely demonstrated and explained in Item 24, Scott Meyers, Effective C++.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 1 hour ago

























                  answered 2 hours ago









                  lubgrlubgr

                  13.8k32052




                  13.8k32052



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55249017%2fwhy-is-implicit-conversion-not-ambiguous-for-non-primitive-types%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Are there any AGPL-style licences that require source code modifications to be public? Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Force derivative works to be publicAre there any GPL like licenses for Apple App Store?Do you violate the GPL if you provide source code that cannot be compiled?GPL - is it distribution to use libraries in an appliance loaned to customers?Distributing App for free which uses GPL'ed codeModifications of server software under GPL, with web/CLI interfaceDoes using an AGPLv3-licensed library prevent me from dual-licensing my own source code?Can I publish only select code under GPLv3 from a private project?Is there published precedent regarding the scope of covered work that uses AGPL software?If MIT licensed code links to GPL licensed code what should be the license of the resulting binary program?If I use a public API endpoint that has its source code licensed under AGPL in my app, do I need to disclose my source?

                      2013 GY136 Descoberta | Órbita | Referências Menu de navegação«List Of Centaurs and Scattered-Disk Objects»«List of Known Trans-Neptunian Objects»

                      Metrô de Los Teques Índice Linhas | Estações | Ver também | Referências Ligações externas | Menu de navegação«INSTITUCIÓN»«Mapa de rutas»originalMetrô de Los TequesC.A. Metro Los Teques |Alcaldía de Guaicaipuro – Sitio OficialGobernacion de Mirandaeeeeeee