Menu
CoddyTech

状態を持つポリシーの合成

Coddyの「C#開発者のためのC」コースのレッスン 40/48。

C#のクロージャは、管理対象オブジェクトを通じてキャプチャした変数を保持します。Cの状態を持つコールバックは、呼び出しを通じて存続する必要がある明示的なコンテキストを借用します。コールバックが自動的にそのコンテキストを存続させることはありません。

状態を持つ動作を渡すには、コンテキストポインターと関数ポインターを組み合わせます。コンテキストは、すべての呼び出しの間存続していなければなりません。

C#の例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {

static void Main(){
int factor=3;Func<int,int> policy=n=>factor*n;Console.WriteLine(policy(4));
}
}

C#の出力:

12

Cの例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
struct Policy {void *context;int (*apply)(void*,int);};
static int multiply(void *context,int n){return *(int*)context*n;}
int main(void) {
int factor=3;struct Policy p={&factor,multiply};printf("%d\n",p.apply(p.context,4));
return 0;
}

Cの出力:

12
challenge icon

チャレンジ

簡単

Policyはcontextを保持し、apply(context,value)を呼び出します。指定されたコールバックを同じcontextで1回呼び出すように、price_with(policy,value)を実装してください。入力はfactorとvalueです。ドライバーはoffsetポリシーも渡して呼び出し回数を確認するため、乗算をハードコードするだけでは不十分です。

ロックされていないソースファイルとヘッダーファイルを編集してください。表示されているロック済みのmain.cから直接呼び出されるため、宣言済みの公開APIとの互換性を保ってください。別のmainを追加しないでください。タスクで範囲が明示的に確認される場合を除き、すべての数値タスク用テストデータはオーバーフローを避けられる小さな値です。指定された出力だけを出力してください。表示されている場合、ドライバーが入力の解析と出力を行います。

自分で試してみよう

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
static int multiply(void *context,int n){return *(int*)context*n;}
typedef struct {int offset,calls;} Counter;
static int shifted(void *context,int n){Counter *p=context;p->calls++;return n+p->offset;}
int main(void){int factor,value;if(scanf("%d%d",&factor,&value)!=2)return 1;Counter c={7,0};if(price_with((Policy){&c,shifted},3)!=10 || c.calls!=1)return 3;printf("%d\n",price_with((Policy){&factor,multiply},value));return 0;}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C#開発者のためのCのすべてのレッスン

自分で練習してみよう: Cオンラインコンパイラ