Casting patterns and operators

This code compiles in CodeGear 2009 and Visual Studio 2010, but not gcc. Why?

class Foo
{
public:
    operator int() const;

    template <typename T> T get() const { return this->operator T(); }
};

Foo::operator int() const
{
    return 5;
}

Error message:

test.cpp: In the member function `T Foo :: get () const ':
test.cpp: 6: error:" const class Foo "does not have a name named" operator T "

+3
source share
4 answers

This is a bug in g ++. operator T- This is an unqualified dependent name (because it is in it T, and the search will differ depending on its type). Therefore, it should be considered when creating the instance. Standard rules

Two names are the same if

  • ...
  • , .

, , , . , GCC

template<typename T, typename>
struct identity { typedef T type; };

class Foo
{
public:
    operator int() const;

    template <typename T> T get() const { 
      return this->identity<Foo, T>::type::operator T(); 
    }
};
+8

, ++, , operator T() operator int(). :

template <typename T> T get() const { return static_cast<T>(*this); }

, , . , operator T(). , .

+4

:

template <typename T> T get() const { return operator T(); }

GCC:

" T", , " " ( '-fpermissive', g++ , uneclared name )

-fmmissive, , T = int

, :

template <typename T> T get() const { return *this; }

.

+2

, . , :

Foo f;
int x = f.get<int>();

:

Foo f;
int x = static_cast<int>(f);

, ( C), .

+2

Source: https://habr.com/ru/post/1741840/


All Articles