Question

Is there a way to pass foo_ around outside of main? I saw something about Boost in another question regarding functors. That looks like it may work. Here's the answer mentioning Boost in that question. If I can, I would like to avoid Boost.

#include <iostream>

int main()
{
    class foo {
        public:
        void operator()() {
            std::cout << "Hello" << std::endl;
        }
    };

    foo foo_;
    foo_();
    return 0;
}
Was it helpful?

Solution

No, currently local types aren't allowed to go into templates (otherwise you could've used boost or std::tr1::function). However, you could maybe do it OOP, where Foo inherits something (that has a virtual opeator() func that your foo implemen ts) and you pass a ptr to Foo around instead.

OTHER TIPS

function local classes cannot be used as template arguments if that's what you mean. This will only be supported by C++0x.

It appears possible to use the address of a static function of a local class. However, operator() must be a non-static member function, hence you'll need to give it a name:

#include <iostream>

template <class T>
void bar(T f)
{
    f();
}

int main()
{
    class foo {
        public:
        static void do_it() {
            std::cout << "Hello" << std::endl;
        }
    };
    bar(&foo::do_it);
    return 0;
}

I don't think it is possible to invoke a member of a class that is not defined in the current scope. The functor in this case retains no state and behaves like a function that takes no parameters and returns no value, so you could assign an instance of it to a raw function pointer. However, it is then no longer a foo: it is just a function pointer.

One solution is to derive foo from a pure virtual base class defined at global scope, such as:

class base
{
public:
    void operator()() { doit(); }
protected:
    virtual void doit() = 0;
};

int main()
{
    class foo
    {
    public:
        void operator()() { doit(); }
    protected:
        virtual void doit()
        {
            std::cout << "Hello" << std::endl;
        }
    };
 }

You can now pass an instance of foo around as base, and the virtual doit() method will be invoked as expected.

EDIT: this does not appear to be valid C++ although some copilers take it without complaint.

well if you have something accepting functors as a template parameter, you could pass anything to it behaving as a functor, although I'm not entirely sure that is what you're after?

template< class tFunctor >
void UseFunctor( const tFunctor& func )
{
  func();
}

int main()
{
  foo foo_;
  UseFunctor( foo_ );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top