Problems with unary_function
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
}
};
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement