7

我正在创建一个模板类D<N>,它有一个返回不同类型的方法(在本例中为 operator()),具体取决于 N 的值。

我只能通过创建两个单独的类声明来完成这项工作,但这是以大量重复代码为代价的。我还尝试创建一个通用基类来将通用的东西放入其中,但我无法让构造函数正确继承,也不知道这会是多么地道......

#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 回答