Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will an Implicit conversion function to self ever get called?

Tags:

c++

Suppose I define an implicit conversion function to myself:

#include <iostream>

class Foo {
 public:
  operator Foo() {
    std::cout << "wha??\n";
    return Foo();
  }
};

void f(Foo f) {}

int main() {
  Foo foo;
  f(foo);
}

Why would I define this? Well I would never write it directly, but it could happen through a template instantiation in a template class I'm writing. If this happens, I hope that defining the conversion function is effectively a no-op and that it is impossible to actually call.

The above program prints nothing (which is great). Is there any circumstance under which this conversion function will actually get called?

like image 250
Josh Haberman Avatar asked Oct 16 '13 05:10

Josh Haberman


1 Answers

It's correct, but will never called, due n3376 12.3.2/1

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)

like image 123
ForEveR Avatar answered Oct 21 '22 03:10

ForEveR