в

Kazan Dev Alliance

Казанское Сообщество Разработчиков Программного Обеспечения

Персональный блог Дмитрия Кальянова

Сопрограммы на C и C++

Сопрограммы — это один из полезных приемов программирования.

Например, в C# сопрограммы могут быть использованы для создания итераторов (см. ключевое слово yield) (но не более — область их применения ограничена итераторами).

Для C и C++ существует интересный способ добавить такую возможность в язык — с помощью макросов.

Собственно, весь код взят со страницы http://www.codepost.org/view/104 и содержит всего совсем немного строчек.

Вот он:

#define cr_context   int __s;
#define cr_init()    __s = 0;
#define cr_start()   switch (__s) { case 0:
#define cr_return(x) { __s = __LINE__; return x; case __LINE__: ; }
#define cr_end()     { break; default: for (;;) ; } } __s = 0; 

И пример его использования:

class foobar_f {
private:
    cr_context;

    // place the variables which need to be remembered between calls here.
    int i;

public:
    foobar_f(void) {
        cr_init();
    }

    // overloading the function application operator "()"
    int operator () (void) {
        cr_start();

        for (i = 0; i < 1337; i++) {
            cr_return(i);
        }

        cr_end();
    }
};

// create a function object, sometimes (incorrectly) called functor.
foobar_f foobar;

printf("%d\n", foobar()); // prints 0
printf("%d\n", foobar()); // prints 1
printf("%d\n", foobar()); // prints 2 

Возможно, будет полезно...

Комментарии

 

doctorsolberg сказал:

Я может просто совсем отвык от С, но в чем преимущества такого подхода перед нормальным процедурным кодом?

December 9, 2006 2:26 PM
 

dvk сказал:

В общем, это упрощает создание функций, которые должны вернуть несколько значений (например, как в C# 2.0 это делают итераторы). В общем, удобная штука для создания совместно работающих процессов.

Из википедии (http://en.wikipedia.org/wiki/Coroutine):

Common uses of coroutines

Coroutines are useful to implement the following:

   * State machines within a single subroutine, where the state is determined by the current entry/exit point of the procedure; this can result in more readable code.

   * Actor model of concurrency, for instance in computer games. Each actor has its own procedures (this again logically separates the code), but they voluntarily give up control to central scheduler, which executes them sequentially (this is a form of cooperative multitasking).

   * Generators, and these are useful for input/output and for generic traversal of data structures.

December 9, 2006 9:27 PM
 

doctorsolberg сказал:

Хм... Спасибо за разъяснение :)

December 10, 2006 12:48 PM
 

Uri сказал:

Спасибо. Как-то не приходил в голову такой простой прием...

December 19, 2006 3:57 PM

Оставить комментарий

(required)  
(optional)
(required)  

© 2007 Kazan Developers Community and Post`s Authors