私はメソッドprintCode()
でC++コードを生成できるC1とC2の2つのクラスを持っています。forループでソースコードを生成
C1* array1[100];
C2* array2[100];
// Create objects to generate code
for (int i = 0; i < 100; i++) {
array1[i] = new C1(i);
array2[i] = new C2(i);
}
[...]
// Generate code
for (int i = 0; i < 100; i++) {
array1[i]->printCode();
array2[i]->printCode();
}
生成されたコード:私はこの代わりに(同じ出力、より小さなコードサイズ)を生成する方法
// f represents a set of operations
// code generated by array1[0], array2[0]
(x[0], x[1], ..., x[n]) := f(0, x[0], x[1], ..., x[n]);
// code generated by array1[1], array2[1]
(x[0], x[1], ..., x[n]) := f(1, x[0], x[1], ..., x[n]);
[...]
// code generated by array1[99], array2[99]
(x[0], x[1], ..., x[n]) := f(99, x[0], x[1], ..., x[n]);
:
C1、C2のオブジェクトを使用して、私は次のようにC++コードを生成することができfor (int i = 0; i < 100; i++)
(x[0], x[1], ..., x[n]) := f(i, x[0], x[1], ..., x[n]);
編集:C1、C2の例定義:
const int n = 1000;
class C1 {
public:
C1(int x) : my_var(x) {}
void printCode() {
for (int i = 0; i < n - 1; i++) {
// func1 is defined in the generated code
// the generated code sees foo(my_var) as a constant
cout << "x[" << i << "] = func1(x[" << i << "], x[" << i + 1 "] + " << bar(my_var) << endl;
}
}
private:
int my_var;
int foo(int x) { ... }
}
C2は似ています。上記のように定義されたC1、C2で
class C2 {
public:
C2(int x) : my_var(x) {}
void printCode() {
for (int i = 0; i < n - 1; i++) {
// func2 is defined in the generated code
// the generated code sees bar(my_var) as a constant
cout << "x[" << i << "] = func2(x[" << i << "], x[" << i + 1 "] + " << bar(my_var) << endl;
}
}
private:
int my_var;
int bar(int x) { ... }
}
、生成されたコードは次のようになります。
// definitions of func1, func2
int func1(int x, int y) { ... }
int func2(int x, int y) { ... }
...
// Code generated by C1(0)
x[0] = func1(x[0], x[1]) + f0; // f0 = C1.foo(0)
x[1] = func1(x[1], x[2]) + f0;
...
x[998] = func1(x[998], x[999]) + f0;
// Code generated by C2(0)
x[1] = func2(x[0], x[1]) + b0; // b0 = C2.bar(0)
x[2] = func2(x[1], x[2]) + b0;
...
x[999] = func2(x[998], x[999]) + b0;
// Code generated by C1(1), C2(1)
// Code generated by C1(2), C2(2)
...
// Code generated by C1(99), C2(99)
私が欲しいもの:
for (int i = 0; i < 100; i++) {
x[0] = func1(x[0], x[1]) + f[i]; // f[i] = C1.foo(i)
x[1] = func1(x[1], x[2]) + f[i];
...
x[998] = func1(x[998], x[999]) + f[i];
x[1] = func2(x[0], x[1]) + b[i]; // b[i] = C2.bar(i)
x[2] = func2(x[1], x[2]) + b[i];
...
x[999] = func2(x[998], x[999]) + b[i];
}
クラス 'C1'とC2がどのように実装されているかについて詳しく述べる必要があります – teivaz
@teivaz C1、C2のコードを追加しました。 – vhl
私が追加した例は明らかに混乱の原因になっています。 'printCode()'の中のforループは、関数が多くのコードを出力することを示しています。私のアプリケーションでは、printCode()を最適化することはできません。 – vhl