7

D<N>N の値に応じて異なる型を返すメソッド (この場合は operator()) を使用して、テンプレート化されたクラスを作成しています。

2 つの別個のクラス宣言を作成することによってのみ、これを機能させることができましたが、これには多くのコードの重複という代償が伴いました。また、共通のものをスローする共通の基本クラスを作成しようとしましたが、コンストラクターを正しく継承させることができず、それがどれほど慣用的であるかもわかりません...

#include <cstdio>

template <int N>
struct D{
    int s;
    D(int x):s(x){}

    int yell(int x){
        printf("N=%d, %d\n", N, s+x);
        return s+x;
    }

    D<N-1> operator()(int x){
        D<N-1> d(yell(x));
        return d;
    }
};

template <>
struct D<1>{
    int s;
    D(int x): s(x){}

    int yell(int x){
        printf("N=%d, %d\n", 1, s+x);
        return s+x;
    }

    int operator()(int x){
        return yell(x);
    }
};


int main()
{
    D<2> f(42);
    printf("%d\n", f(1)(2));
    return 0;
}

コードの見栄えを良くするにはどうすればよいですか?

4

2 に答える 2

8

不思議なことに繰り返されるテンプレートパターンを使用できます。

template<int N, template<int> typename D> struct d_inner {
    D<N-1> operator()(int x) {
        return D<N-1>(static_cast<D<N>*>(this)->yell(x));
    }
};
template<template<int> typename D> struct d_inner<1, D> {
    int operator()(int x) {
        return static_cast<D<1>*>(this)->yell(x);
    }
};

template <int N> struct D : public d_inner<N, D> {
    int s;
    D(int x):s(x){}

    int yell(int x){
        printf("N=%d, %d\n", N, s+x);
        return s+x;
    }
};

この特定のオブジェクトの有用性または目的がテンプレート化されているのを私が見ているわけではありませんが、簡単にそうすることはできません。

于 2011-06-02T21:10:19.057 に答える
4

見栄えが良いかどうかはわかりませんが、ソースコードの重複を回避できます。

 // Find a name for this ...
template<int N, template<int M> class X>
struct foo {
  typedef X<N> type;
};
template< template<int M> class X >
struct foo<0,X> {
  typedef int type;
};

template <int N>
struct D{
  int s;
  D(int x):s(x){}

  int yell(int x){
    printf("N=%d, %d\n", N, s+x);
        return s+x;
  }

  typename foo<N-1,D>::type
  operator()(int x){
    return typename foo<N-1,D>::type(yell(x));
  }
};
于 2011-06-02T21:11:03.450 に答える