This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

pointer to template member function


Hi, I´ve come across the following code, which g++ refuses to compile:

// ---
struct A
{
    void a() {}
};

struct B : A
{
    template <class T> void b() {}
};

typedef void (A::* ptr)();

int main()
{
    ptr x = &A::a, // 
	y = static_cast<ptr>(&B::b<int>); // g++ chokes here
}
// ---

G++ says that 

error: invalid static_cast from type 
	'<unresolved overloaded function type>' to type 'void (A::*)()'

But if I make void b() a non-template class and modify the cast to
static_cast<ptr>(&B::b) it compiles fine. If this is valid, why the
template case isn't?

I'd really say that either casts shouldn't be valid, because in the
non-template case, I could do:

  A a;
  (a.*x)(); // fine, x points to a member of A, and we are using it with
	    // an instance of A.

  (a.*y)(); // this will have unpredictable results if B::b relies on
	    // a B's attribute, because we're using B::* with an A
	    // instance. static_casts should be 'safe', aren't they?

Fortunately, both cases fail when using the default cast without
static_cast. In the template case, compilation fails with:

error: no matches converting function 'b' to type 'void (struct A::*)()'
error: candidates are: template<class T> void B::b()

And in the non template case, compilation fails with:

error: cannot convert 'void (B::*)()' to 'void (A::*)()' in
initialization


Thanks,
    Rodolfo Lima.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]