力業Tuple

BoostのTupleを真似てみました。

#region Using directives

using System;
using System.Collections.Generic;
using STL.Generic;
using Result = STL.Generic.Tuple<int, int, int, double>;

#endregion

class Program
{
    // 型なしタプル
    static Tuple Calc4_1(int x, int y)
    {
        return Tuple.Make(x + y, x - y, x * y, (double)x / y);
    }

    // 型ありタプル
    static Result Calc4_2(int x, int y)
    {
        return Tuple.Make<Result>(x + y, x - y, x * y, (double)x / y);
    }

    static void Main(string[] args)
    {
        int add, sub, mul;
        double div;

        add = sub = mul = 0;
        div = 0.0;

        // 型なしタプルはインデクサでアクセス
        Tuple t1 = Calc4_1(3, 5);
        for (int i = 0; i < t1.Length; ++i)
            Console.Write("{0} ", t1[i]);
        Console.WriteLine();

        // 型ありタプルはフィールドを持つ
        Result t2 = Calc4_2(3, 5);
        Console.WriteLine("{0} {1} {2} {3}", t2._0, t2._1, t2._2, t2._3);

        // 型ありタプルへキャスト
        Result t3 = t1 as Result;

        // タプルから値を取得
        t3.Tie(ref add, ref sub, ref mul, ref div);
        Console.WriteLine("{0} {1} {2} {3}", add, sub, mul, div);

        Console.ReadLine();
    }
}
/* 結果
8 -2 15 0.6
8 -2 15 0.6
8 -2 15 0.6
 */

例はBoost本から。実装は型パラメータが1〜10個のTupleの羅列なので、ソースを貼り付ける気になりません。(^^;