递归c型数组解引用模板

时间:2018-12-16 14:02:07

标签: arrays templates

Am正在尝试制作模板函数,如果仍然可以递归地解除对数组的引用,但是在测试之前已经对其进行了解除引用。 我该怎么办?

template <typename T>
int countLayer(T &a){
    if (sizeof(a)/sizeof(int)) return countLayer(*a)+1;
return 1;}

即使是一个错误的人

template <typename T>
int countLayer(T &a){
    if (false) return countLayer(*a)+1;
return 1;}

只是环顾四周,发现type_traits, 但不要将任何额外的库用作必不可少的功能。

2 个答案:

答案 0 :(得分:0)

...好吧找到它了

int countLayer(int &a){ return 0; }
int countLayer(double &a){ return 0; }
int countLayer(char &a){ return 0; }

template <typename T>
int countLayer(T &a){
    return 1+countLayer ( *a);
return 1;}

.. so这样,已经完全定义了countLayers-Funktion的常规一元类型,并且只需要生成数组,因此我避免了无法取消引用一元类型,这很酷; P ..显然这是相当危险的,因为我可以传递任何未声明的类型,但是仍然可以。 ...这个想法的总和不是为了计算层数而是为了产生一个通用的输出...某种程度地处理数组中的每个元素。

感谢“ n.m”,但在那里没有用-但是我明白了..它基本上是一种可以使用模板的constexpr,但是请证明我错了...请; P 反正为“ n.m”欢呼

答案 1 :(得分:0)

..只是一个例子: 这个:

void printArray(const int (&a)[2][2][4]){
    cout<<'{'; bool aAf=true;
    for (const int (&aA)[2][4]: a){         if (aAf) aAf=false; else cout<<", "; cout<<'{'; bool aBf=true;
        for (const int (&aB)[4]: aA){       if (aBf) aBf=false; else cout<<", "; cout<<'{'; bool aCf=true;
            for (const int (&aC): aB){      if (aCf) aCf=false; else cout<<", ";
                cout<<aC;}
            cout<<'}'; }
        cout<<'}'; }
    cout<<"}\n";    
}

.. gets减少为:

void printA(int &a) { cout<< a; };

template <typename T>
void printA(T &a) {
    cout << '{';
    bool first=true;
    for (auto &aS: a){  if (first) first=false; else cout<<", ";
                        printA(aS); }
    cout << '}';                    
}

..并且只要一元类型存在,就可以很好地处理任何类型的数组

..很好,很容易知道; P