CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 65

Hybrid View

  1. #1
    Join Date
    Apr 2009
    Posts
    1,355

    [RESOLVED] template for events

    i'm doing these template:

    Code:
    template <class T, class A>
    class events : public T
    {
    public:
        events(){}
        ~events(){}
        bool operator==( const T& aTee ) const     // Explicit cast
        { return (aTee == *(static_cast<T*>(this))); }
        const T* getTpart() const { return this; } // Implicit cast
    }A;
    but i get some errors:
    "C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|15|error: declaration of 'events<T, A> A'|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|6|error: shadows template parm 'class A'|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|15|error: template declaration of 'events<T, A> A'|
    ||=== Build finished: 3 errors, 0 warnings (0 minutes, 2 seconds) ===|"
    why, in normal class, i use 'A' without a problem and here i get errors?

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: template for events

    Quote Originally Posted by Cambalinho View Post
    i'm doing these template:

    Code:
    template <class T, class A>
    class events : public T
    {
    public:
        events(){}
        ~events(){}
        bool operator==( const T& aTee ) const     // Explicit cast
        { return (aTee == *(static_cast<T*>(this))); }
        const T* getTpart() const { return this; } // Implicit cast
    }A;
    but i get some errors:
    "C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|15|error: declaration of 'events<T, A> A'|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|6|error: shadows template parm 'class A'|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|15|error: template declaration of 'events<T, A> A'|
    ||=== Build finished: 3 errors, 0 warnings (0 minutes, 2 seconds) ===|"
    why, in normal class, i use 'A' without a problem and here i get errors?
    It would help if you actually posted a main() function that instantiates the template. No one knows why a template gives syntax errors unless we see what you're instantiating the template with.

    Also, very few, if any C++ programmers uses this syntax:
    Code:
    class whatever
    {
      ///
    } A;
    The declaration of something directly after the class is hardly ever used. This adds more confusion as events is a class based on a template.

    Why not just do something simple that everyone can understand -- define the templated class, and then within the codebase, declare instances of the class.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: template for events

    Quote Originally Posted by Cambalinho View Post
    Code:
    template <class T, class A>
    class events : public T
    {
      // ...
    }A;

    Even if it might be possible to create a concrete instance of a template under a name that's identical to one of the template parameter names (which looks pretty weird to me by itself) using a syntax remotely similar to the one used here: How could the compiler ever be able to infer the concrete types represented by T and A here!?
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  4. #4
    Join Date
    Apr 2009
    Posts
    1,355

    Re: template for events

    Quote Originally Posted by Eri523 View Post
    Even if it might be possible to create a concrete instance of a template under a name that's identical to one of the template parameter names (which looks pretty weird to me by itself) using a syntax remotely similar to the one used here: How could the compiler ever be able to infer the concrete types represented by T and A here!?
    thanks to both.
    let ask in other(maybe i must give on that thot): how can i change the functions using objects?
    someone spok(it's correct?) me about functors. can anyone please tell me more?

  5. #5
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: template for events

    Put short, a functor is an object (i.e. an inctance of a class) that overloads operator()(). See, for instance, http://www.parashift.com/c++-faq/fun...nctionoid.html
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  6. #6
    Join Date
    Apr 2009
    Posts
    1,355

    Re: template for events

    Quote Originally Posted by Eri523 View Post
    Put short, a functor is an object (i.e. an inctance of a class) that overloads operator()(). See, for instance, http://www.parashift.com/c++-faq/fun...nctionoid.html
    i have 1 question for don't 'lose my self':
    (see these class... see the what i mean)
    Code:
    #include <iostream>
    
    using namespace std;
    
    class test
    {
          virtual void functorfunname(){};
          test()
          {
                functorfunname();
          }
    };
    
    
    test a;
    
    void a::functorfunname()
    {
          cout << "hello world";
    }
    
    int main()
    {
    
       cin.get();
       return 0;
    }
    (these code have 1 error with functorfunname() declaration)
    now the object can do that?(change the function)

  7. #7
    Join Date
    Apr 1999
    Posts
    27,449

    Re: template for events

    Quote Originally Posted by Cambalinho View Post
    i have 1 question for don't 'lose my self':
    (see these class... see the what i mean)
    Do you know how to overload operator()()? Your attempt at it indicates you haven't read the mountain of information on how to overload the operator, and just guessing what a functor looks like.

    Regards,

    Paul McKenzie

  8. #8
    Join Date
    Apr 2009
    Posts
    1,355

    Re: template for events

    Quote Originally Posted by Paul McKenzie View Post
    Do you know how to overload operator()()? Your attempt at it indicates you haven't read the mountain of information on how to overload the operator, and just guessing what a functor looks like.

    Regards,

    Paul McKenzie
    i'm trying without sucess:
    Code:
    #include <iostream>
    //#include "console.h"
    
    
    using namespace std;
    
    
    class events
    {
        public:
        void operator()(...);
    };
    
    class test
    {
        public:
        events a;
        test()
        {
            a();
        }
    };
    
    
    int main()
    {
        test a;
        a.a(){cout << "hello world"};
    
        return 0;
    }
    i must read more about it

  9. #9
    Join Date
    Apr 1999
    Posts
    27,449

    Re: template for events

    Quote Originally Posted by Cambalinho View Post
    i'm trying without sucess:
    Why not take a working example and study it?
    Code:
    a.a(){cout << "hello world"};
    What is that supposed to do? Did you make this up on your own? No book or tutorial on function objects has anything looking like that.
    Code:
    #include <algorithm>
    
    // function object that determines order of items (ascending or descending)
    template <typename T>
    struct Sorter
    {
        bool bAscending;
        Sorter(bool isAscending ) : bAscending(isAscending) {}
        bool operator() (const T& value1, const T& value2) const
        {
             if ( bAscending )
                  return value1 < value2;
             return value2 < value1;
         }
    };
    
    int main()
    {
         int arr[] = {1, 3, -4, 100, 34, 5, 0};
         const int numElements = sizeof(arr) / sizeof(arr[0]);
    
         // sort arr in ascending order
         std::sort(arr, arr + numElements, Sorter<int>(true));
         
         // sort arr in descending order
         std::sort(arr, arr + numElements, Sorter<int>(false));
    }
    In the example above, the sort algorithm will call the Sorter's operator() by just invoking function call syntax.
    In addition:

    http://www.cprogramming.com/tutorial...ts-in-c++.html
    http://www.dreamincode.net/forums/to...ction-objects/

    Regards,

    Paul McKenzie

  10. #10
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: template for events

    A word to the wise.

    Design first, code second, test/debug last. Don't try to be too ambitious with the design. Just because the c++ language provides a 'feature' doesn't mean it has to be used unless it is appropriate for what you are trying to achieve. The further you delve into the dusty corners of c++, the more you need to understand what is going on and the less you can get away with 'winging it' with the syntax.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  11. #11
    Join Date
    Apr 2009
    Posts
    1,355

    Re: template for events

    now works fine... thanks for all to all
    Code:
    #include <functional>
    #include <vector>
    #include <iostream>
    
    
    template<typename... Args>
    class events
    {
    public:
        typedef std::function<void(Args... args)> OnSomethingHandler;
        events(OnSomethingHandler Handler)
        {
            handlers_.push_back(Handler);
        }
        void operator ()(Args... args)
        {
            for(auto i = handlers_.begin(); i != handlers_.end(); ++i)
                (*i)(args...);
        }
    private:
        std::vector<OnSomethingHandler> handlers_;
        void AddHandler(OnSomethingHandler Handler)
        {
            handlers_.push_back(Handler);
        }
        void TriggerEvents()
        {
            for(auto i = handlers_.begin(); i != handlers_.end(); ++i)
                (*i)();
        }
    };
    
    
    int main()
    {
        events<int, int> foo([](int a, int b)
        {
            std::cout << (a+b) << "\n";
        });
        foo(5,6);
    }
    
    //or
    
    int main()
    {
        events<> foo([]()
        {
            std::cout << "hello world" << "\n";
        });
        foo();
    }
    thanks for all... to all

  12. #12
    Join Date
    Apr 2009
    Posts
    1,355

    Re: template for events

    now i'm testing inside of a class, but i get several errors
    Code:
    //events.h
    #ifndef events_H_INCLUDED
    #define events_H_INCLUDED
    
    #include <functional>
    #include <vector>
    
    template <typename ... b>
    class events
    {
    public:
        typedef std::function<void(b...argx )> OnSomethingHandler;
    
        events(OnSomethingHandler Handler)
        {
            handlers_=Handler;
        }
    
        void operator ()(b... args)
        {
            handlers_(args...);
        }
        events& operator = (OnSomethingHandler Handler)
        {
            handlers_ = Handler;
            return *this;
        }
    
    private:
        OnSomethingHandler handlers_;
    
    };
    
    #endif // events_H_INCLUDED
    and how i use it:

    Code:
    #include <iostream>
    #include "events.h"
    
    using namespace std;
    
    class test
    {
    private:
        int x=20;
        int y=0;
    public:
        events<int, int> created;
        events<int, int> move;
    
        test()
        {
            created([](int a, int b) { ; });
            created(x,y);
    
        }
    
        void setX(int s)
        {
            x=s;
            move=([](int a, int b) { ; });
            move(x,y);
        }
    };
    
    int main()
    {
        test a;
        a.created=[](int a, int b)
        {
    
            if (b==0)
                cout << "you can't divide by zero";
            else
                cout << (a/b);
    
        };
        a.created(8,2);
        a.Move=[](int a)
        {
            if (a<0)
                cout << "hide";
            else
                cout << "show";
        }
        a.setX(10);
       cin.get();
    }
    "what i need is the class call the events object and pass to it same values(depending on object class members).
    but seems that i get several errors:
    like declaring 2 events
    heres the errors messages:
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp||In constructor 'test::test()':|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|16|error: no matching function for call to 'events<int, int>::events()'|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|16|note: candidates are:|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|13|note: events<b>::events(events<b>::OnSomethingHandler) [with b = {int, int}; events<b>::OnSomethingHandler = std::function<void(int, int)>]|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|13|note: candidate expects 1 argument, 0 provided|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|8|note: events<int, int>::events(const events<int, int>&)|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|8|note: candidate expects 1 argument, 0 provided|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|8|note: events<int, int>::events(events<int, int>&&)|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|8|note: candidate expects 1 argument, 0 provided|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|16|error: no matching function for call to 'events<int, int>::events()'|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|16|note: candidates are:|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|13|note: events<b>::events(events<b>::OnSomethingHandler) [with b = {int, int}; events<b>::OnSomethingHandler = std::function<void(int, int)>]|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|13|note: candidate expects 1 argument, 0 provided|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|8|note: events<int, int>::events(const events<int, int>&)|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|8|note: candidate expects 1 argument, 0 provided|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|8|note: events<int, int>::events(events<int, int>&&)|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|8|note: candidate expects 1 argument, 0 provided|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|17|error: no match for call to '(events<int, int>) (test::test()::__lambda0)'|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|8|note: candidate is:|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|18|note: void events<b>:perator()(b ...) [with b = {int, int}]|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\events.h|18|note: candidate expects 2 arguments, 1 provided|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp||In function 'int main()':|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|43|error: 'class test' has no member named 'Move'|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|50|error: expected ';' before 'a'|
    ||=== Build finished: 5 errors, 0 warnings (0 minutes, 6 seconds) ===|"
    what i'm doing wrong?

  13. #13
    Join Date
    Apr 1999
    Posts
    27,449

    Re: template for events

    Quote Originally Posted by Cambalinho View Post
    now i'm testing inside of a class, but i get several errors
    This is exactly what happens when you don't learn basic C++, and instead want to use advanced syntax without a proper track of learning the C++ language.

    Look at this example:
    Code:
    class foo
    {
        public:
           foo(int x);
    };
    
    class someClass
    {
        foo m_foo;
    };
    
    int main()
    {
       someClass s;
    }
    There is an error in the code. Can you fix the compile error without changing class foo? The hint is that the error with the code above and the error you have are the same.

    Also, note that this is basic C++ knowledge. A beginner in the language must know how to fix that error -- it is not advanced, doesn't use lamdas, templates, or any of that new C++ 11 stuff you're throwing around.

    Regards,

    Paul McKenzie

  14. #14
    Join Date
    Apr 2009
    Posts
    1,355

    Re: template for events

    Quote Originally Posted by Paul McKenzie View Post
    This is exactly what happens when you don't learn basic C++, and instead want to use advanced syntax without a proper track of learning the C++ language.

    Look at this example:
    Code:
    class foo
    {
        public:
           foo(int x);
    };
    
    class someClass
    {
        foo m_foo;
    };
    
    int main()
    {
       someClass s;
    }
    There is an error in the code. Can you fix the compile error without changing class foo? The hint is that the error with the code above and the error you have are the same.

    Also, note that this is basic C++ knowledge. A beginner in the language must know how to fix that error -- it is not advanced, doesn't use lamdas, templates, or any of that new C++ 11 stuff you're throwing around.

    Regards,

    Paul McKenzie
    the class foo have 1 construtor witth 1 argument. so the
    Code:
     foo m_foo;
    must be:
    Code:
     foo m_foo(3);
    or with a int variable.
    thanks for that thot
    my problem was that and copy from 1 person that help me, and i don't see that point

    let me ask anotherthing:
    i more or less know. but why the created() isn't showed?
    Code:
    #include <iostream>
    #include "events.h"
    
    using namespace std;
    
    class test
    {
        int x=20;
        int y=50;
    public:
        events<> created{[]() { ; }};
        events<int, int> moved{[](int a, int b) { ; }};
    
        test()
        {
            created();
        }
    
        void setx(int s)
        {
            x=s;
            moved(x,y);
        }
    };
    
    int main()
    {
        test a;
        a.created=[]()
        {
            cout << "hello world";
        };
        a.moved=[](int a, int b)
        {
            cout << "moved to: x = " << a << " y = " << b;
    
        };
        a.setx(100);
    
       cin.get();
    }
    it's because i changed the created() after i create 'a'?

  15. #15
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: template for events

    must be:
    Code:
     foo m_foo(3);
    The c++ language stipulates that 'only const static integral data members can be initialized inside a class or struct'. This statement violates all three! So your suggested solution is not correct. As Paul states in post #17, anyone who is programming with c++ classes must be able to easily fix this problem. It is not complicated, it just requires some basic understanding of classes.

    If you don't know how to do this, then I strongly suggest that you take some time out from writing your 'clever' code and learn the basics of the c++ language. You cannot 'guess' with c++. You have to know and understand which requires learning. Doing this may not be as 'interesting' as writing template code using the new features of c++11 but the effort put into it will repay you later.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured