Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ unexpected implict conversion

Tags:

c++

casting

The following code compiles due to the implicit conversion for char. I'm not sure why since the only implicit conversion I would expect (and expect to fail) is from char const* to size_t.

#include <cstddef>

struct foo
{
    int operator[](size_t i) const { return 1; }
    operator char() const { return 'a'; }
};

int main()
{
    foo f;
    f["hello"]; // compilation error desired here
}

What is the implicit conversion here that allows this to compile? If I remove operator char or make it explicit then the compile fails at the desired location.

The class that this code is extracted from really does need both the implicit conversion and the operator[]. So is there a way I can prevent the behaviour without making the conversion explicit?

like image 229
marack Avatar asked Sep 23 '14 05:09

marack


1 Answers

The reason that line compiles is that, with the implicit conversion, it can be reinterpreted as 'a'["hello"];, which in turn is the same as writing *(('a')+("hello")); which also compiles.

Excerpt for the Standard:

5.2.1 Subscripting:

... The expression E1[E2] is identical (by definition) to *((E1)+(E2)) ...

The easiest workaround without making the conversion operator explicit is to declare the offending subscript operator as deleted:

struct foo
{
  operator char() const { return 'a'; }
  int operator[](size_t i) const { return 1; }

  // prevent accidental use of foo["hello"]
  int operator[](char const*) const = delete;
};
like image 51
imreal Avatar answered Nov 03 '22 09:11

imreal