Walking around a nested functor (C ++)

Is there a way to pass foo_ outside the main? I saw something about Boost in another question regarding functors. It seems like this might work. Here's an answer that mentions Boost in this question. If possible, 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;
}
+3
source share
5 answers

No, currently local types are not allowed to enter templates (otherwise you could use boost or std :: tr1 :: function). However, you could do this OOP, where Foo inherits something (which has a virtual operator function () that your foo implemen ts), and you pass ptr instead of Foo.

+4
source

, , . ++ 0x.

+1

-, . operator() -, :

#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;
}
+1

: , , ++, .

, -, , -, , , , ?

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

int main()
{
  foo foo_;
  UseFunctor( foo_ );
}
0

, , . , , . , foo: .

foo , , :

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;
        }
    };
 }

foo , virtual doit() , .

0

Source: https://habr.com/ru/post/1721000/


All Articles