Mar 18
Courtesy of my current reading, Herb Sutter’s More Exceptional C++, I have learned that it is possible in C++ to write a function which returns a pointer to itself using a somewhat sneaky trick:
class FuncPtr_;
typedef FuncPtr_ (*FuncPtr)();
class FuncPtr_
{
public:
FuncPtr_(FuncPtr p) : m_p(p) {}
operator FuncPtr() { return m_p; }
private:
FuncPtr m_p;
};
FuncPtr_ f() { return f; }
OK, I admit that this function doesn’t exactly return a pointer to itself—it returns an instance of a class which is implicitly convertible to a pointer to the original function—but it accomplishes the same thing in effect. For example:
FuncPtr p = f(); p(); // or (*p)();
Recent Comments