mercredi 6 février 2019

Defining explicit conversion - possible GCC bug

I'm trying to define a simple explicit conversion in C++11, separately from the header file, using GCC 4.8.5 (CentOS 7's default):

foo.h:

#ifndef _foo_h_
#define _foo_h_

typedef struct {
    int x;
    explicit operator int() const;
} A;

#endif

foo.cpp:

#include "foo.h"

A::operator int() const
{
    return this->x;
};

main.cpp:

#include "foo.h"

int main(int,char**)
{
    A a{1};
    int b = (int)a - 1;
    return 0;
}

GCC 4.8.5 inexplicably fails to link this code:

$ g++ -std=c++11 foo.cpp main.cpp
/tmp/cc5osctA.o: In function `main':
main.cpp:(.text+0x1e): undefined reference to `A::operator int() const'
collect2: error: ld returned 1 exit status

However, if I use any version of GCC >= 5 (e.g. GCC 5.3.1 from RHEL's devtoolset-4 software collection), it works, as I'd expect it to:

$ scl enable devtoolset-4 "g++ -std=c++11 foo.cpp main.cpp"
### (no linker errors, b == 0 when running)


Is this a bug in GCC 4.8.5's C++11 support? Or is my code malformed?

Aucun commentaire:

Enregistrer un commentaire