[RESOLVED] template for events
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 5 1234 ... LastLast
Results 1 to 15 of 65

Thread: [RESOLVED] template for events

  1. #1
    Join Date
    Apr 2009
    Posts
    644

    [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,427

    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,585

    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
    644

    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,585

    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
    644

    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,427

    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
    644

    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,427

    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
    Join Date
    Apr 2009
    Posts
    644

    Re: template for events

    Quote Originally Posted by Paul McKenzie View Post
    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
    now i have the code working:
    Code:
    #include <iostream>
    //#include "console.h"
    #include <functional>
    #include <vector>
    
    using namespace std;
    //#define  lambda []()
    
    template <typename ... b>
    class events
    {
    public:
        typedef std::function<void(b...argx )> OnSomethingHandler;
    
        events(OnSomethingHandler Handler)
        {
            handlers_=Handler;
        }
    
    
        void operator ()()
        {
            handlers_();
        }
    
    private:
        OnSomethingHandler handlers_;
    
    };
    
    int main()
    
    {
    
        events<> my_foo([]() mutable throw(){
            std::cout << "hello world\t"  << std::endl;
        });
    
    
        my_foo();
    
        return 0;
    }
    but how can i put it to work for several parameters
    can anyone advice me?

  11. #11
    Join Date
    Apr 1999
    Posts
    27,427

    Re: template for events

    Quote Originally Posted by Cambalinho View Post
    but how can i put it to work for several parameters
    Why "several parameters"?

    Do you know that the functor doesn't just call functions? It is an entire class or struct that can contain anything you want in it. Look at my sort() example.

    So again, why "several parameters"? Let the functor be your "several parameters".

    Regards,

    Paul McKenzie

  12. #12
    Join Date
    Apr 2009
    Posts
    644

    Re: template for events

    Quote Originally Posted by Paul McKenzie View Post
    Why "several parameters"?

    Do you know that the functor doesn't just call functions? It is an entire class or struct that can contain anything you want in it. Look at my sort() example.

    So again, why "several parameters"? Let the functor be your "several parameters".

    Regards,

    Paul McKenzie
    i'm sorry.. but i'm trying

    Code:
    #include <iostream>
    //#include "console.h"
    #include <functional>
    
    using namespace std;
    //#define  lambda []()
    
    template <typename ... T>
    class events
    {
    public:
        typedef std::function<void(T ... a)> OnSomethingHandler;
    
        events(OnSomethingHandler Handler)
        {
            handlers_=Handler;
        }
    
    
        void operator() ( T& ... value1)
        {
             handlers_();
         }
    
    private:
        OnSomethingHandler handlers_;
    
    };
    
    int main()
    
    {
    
        events<int, int> my_foo ([](int a, int b)
        {
            std::cout << "hello world\t"  << std::endl;
        });
    
    
    
        my_foo(5,6);
    
        return 0;
    }
    errors:

    "C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp||In function 'int main()':|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|41|error: no match for call to '(events<int, int>) (int, int)'|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|9|note: candidate is:|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|20|note: void events<T>:perator()(T& ...) [with T = {int, int}]|
    C:\Users\Joaquim\Documents\CodeBlocks\My Class\main.cpp|20|note: no known conversion for argument 1 from 'int' to 'int&'|
    ||=== Build finished: 1 errors, 0 warnings (0 minutes, 1 seconds) ===|"

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

    Re: template for events

    Quote Originally Posted by Cambalinho View Post
    i'm sorry.. but i'm trying
    It looks like you're just throwing syntax around, hoping something works. There seems to be very little, if any design done in what you're doing.

    On a high-level, what are you trying to achieve? I have no idea what you're trying to do -- how about explaining what your goal is with this code?

    My advice to you is to learn design first. For example, this last thread you were in shows the difference between throwing C++ code around with very little thought, and having a design in mind and use C++ paradigms that are commonly known. Look how I solved the problem compared to your original code:

    http://forums.codeguru.com/showthrea...-function-name

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; October 15th, 2013 at 04:01 PM.

  14. #14
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,396

    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. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  15. #15
    Join Date
    Apr 2009
    Posts
    644

    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

Page 1 of 5 1234 ... 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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center