本文介绍了代码复制和模板专门化(当专门函数具有不同的返回类型时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个模板类 D< N> ,在这种情况下使用方法(operator())返回不同的类型,取决于N的值。

I am creating a templated class D<N>, with a method (operator(), in this case) that returns different types, depending on the value of N.

我只能通过创建两个单独的类声明来实现这个功能,但这是以大量代码重复为代价的。我也试图创建一个公共的基类来抛出普通的东西,但我不能让构造函数继承的权利,不知道如何惯用的,以及...

I could only make this work by creating two separate class declarations, but this came at the cost of a lot of code duplication. I also tried to create a common base class to throw the common stuff into, but I couldn't get the constructor to inherit right and don't know how idiomatic that would be as well...

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

如何让我的代码更好看?

How can I make my code better looking?

推荐答案

您可以使用Curiously Recurring Template Pattern。

You can use the 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;
    }
};

不是我看到这个特定对象的模板化的实用程序或目的, be。

Not that I see the utility- or purpose- of this particular object being templated, it could easily not be.

这篇关于代码复制和模板专门化(当专门函数具有不同的返回类型时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 11:59