数组的部分模板专业化 [英] Partial template specialization for arrays

查看:149
本文介绍了数组的部分模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为此搜索,但找不到类似的问题。如果有一个请关闭这个问题。
这不是我真正的代码,只是一个例子来演示: -

Seached for this, but can't find a similar question. If there is one please close this question. This isn't my real code, just an example to demonstrate :-

#include <iostream>

// Normal template class with a destructor
template <class T> class Test
{
public:
    ~Test() { std::cout << "Normal \n";}
};

// Partial specialization for arrays
template<class T> class Test<T[]>
{
public:
    ~Test() { std::cout << "Array \n"; }
};


int main()
{
    Test<int[3]> i;
}

当我编译时,数组的专用版本。如果我用

When I compile this it does not call the specialized version for arrays. If I replace the template with

template<class T> class Test<T[3]>
{
public:
    ~Test() { std::cout << "Array \n"; }
};

然后它会调用专业化,但我想要调用任何数组不仅仅是指定大小的数组。有没有办法写一个专门用于所有数组?

Then it does call the specialization but I want this to be called for any array not just ones of a specifed size. Is there any way to write a specialization that gets used for all arrays?

推荐答案

使用一个额外的非类型参数捕获大小:

Capture the size with an additional non-type parameter:

#include <iostream>

template <class T> class Test
{
public:
    ~Test() { std::cout << "Normal \n";}
};

template<class T, size_t N> class Test<T[N]>
{
public:
    ~Test() { std::cout << "Array " << N << '\n'; }
};

int main()
{
    Test<int[3]> i;  // Array 3
    Test<int[5]> j;  // Array 5
}

这篇关于数组的部分模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆