passing virtual member function to templates

G

g3rc4n

is it possible to do something like this

template<class T, class FUN>
void foo(T& t, const FUN& f){
f(t);
}
template<class T, class FUN>
void fooo(T& t, const FUN& f){
t->f();
}
struct base{
virtual ~base(){}
virtual void say()=0;
};
struct dir : public base{
void say(){
std::cout << "hi" << std::endl;
}
};
void bar(){
base* ptr = new dir;
foo(ptr,std::mem_fun(base::say));
delete ptr;
}

or are virtual functons something that templates can't handle?
 
G

g3rc4n

thanks got it sussed

template<class T, class FUN>
void foo(T& t, FUN f){
(*t.*f)();
}
struct base{
virtual ~base(){}
virtual void say()=0;
};
struct dir : public base{
void say(){
std::cout << "hi" << std::endl;
}
};
void bar(){
base* ptr = new dir;
foo(ptr,&base::say);
}


g++ doesn't like FUN& because it doesn't like base::*&
 
G

g3rc4n

Why is 't' a reference?  You could just drop the '&' altogether, no?
The code in the function requires 't' to be a dereferenceable entity
(like a pointer or an iterator).

because i want to do an operation on t i don't want to do an operation
on a new object, thats the whole point of member functions you noob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top