Sign in to follow this  
Dogmatron

Problems with unary_function

Recommended Posts

Dogmatron    122
I'm doing a small project where I'm storing unary function pointers in a pair object. Does anyone know why the following code doesn't work? typedef std::unary_function<void, float> ufun; typedef std::pair<float, const ufun*> HeapNode; PrintTime printTime; printTime(1000); // works HeapNode node(1000, &printTime); *(node.second)(1000); // error ufun func = *(node.second); func(1000); // error I get a "term does not evaluate to a function" error in Visual Studio. The PrintTime class looks like: class PrintTime : public std::unary_function<void, float> { public: void operator() (float time) const { std::cout << time << std::endl; } bool operator == (const std::unary_function<void, float> &fun) { return this == &fun; } };

Share this post


Link to post
Share on other sites
Extrarius    1412
You're trying to have runtime polymorphism, but going about it the wrong way.

Put simply, a pointer to a unary_function can only hold a pointer to a unary_function. "printTime" is not a unary_function, it's a "PrintTime", but the compiler will convert it for you since "PrintTime" has unary_function as a base class. I believe that "unary_function" does not define it's function call operator, which is what is causing the error.

You could either use the "virtual" keyword to create your own class heirarchy, or use boost::function, which I think handles what you want.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this