我正在创建一个模板化类 D<N> ,其方法(在本例中为 operator())根据 N 的值返回不同类型。

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

#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;
}

如何让我的代码更好看?

最佳答案

您可以使用 Curiously Recurring Template Pattern。

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;
    }
};

并不是说我看到了这个特定对象被模板化的效用或目的,它很容易不是。

关于c++ - 代码重复和模板特化(当特化函数有不同的返回类型时),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6220337/

10-11 22:48
查看更多