1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Genericsでテンプレートの特殊化みたいなことをする

Posted at

結論

https://stackoverflow.com/a/29379250 に載ってる方法で、1回分の仮想関数の呼び出しコストが増えるけどGenericsの特殊化みたいなことができる。

どういうことか

↓のようなコードを書くと、 Hoge の型引数 Tintdouble のときは Hoge<T>.P.Func はなんらかの値を返してくれるけど、それ以外の場合は NotSupportedException を投げるようになる。

Hoge.PIHoge<int>IHoge<double> にしかキャストできないので、

  • Tintdouble のとき、 Hoge<T>.PHoge.P で初期化される
  • T がそれ以外の場合は Hoge.P as IHoge<T>null になるので、 Hoge<T>.Pnew Hoge<T>() で初期化される

というように、Tintdouble のときだけ Hoge<T>.P がGenericじゃない方の Hoge で初期化されるのでこうなる。

public interface IHoge<T>
{
    T Func(T value);
}

public class Hoge<T> : IHoge<T>
{
    public static readonly IHoge<T> P = Hoge.P as IHoge<T> ?? new Hoge<T>();

    public T Func(T value)
    {
        throw new NotSupportedException();
    }
}

public class Hoge : IHoge<int>, IHoge<double>
{
    public static readonly Hoge P = new Hoge();

    public int Func(int value)
    {
        return value;
    }
    public double Func(double value)
    {
        return value;
    }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?