用的unique_ptr&LT工作; INT []&gt;中矢量&lt; INT&gt;和INT []在模板化功能 [英] Work with unique_ptr<int[]>, vector<int>, and int[] in a Templatized Function
问题描述
说,我有3个变量:
vector<int> vec(3);
int stat[3];
auto dyn = make_unique<int[]>(3);
我可以初始化任何这些,如果我知道的大小是3:
I can initialize any of these if I know the size is 3:
for(auto i = 0; i < 3; ++i) X[3] = i;
其中, X
是 VEC
,与stat
或 DYN
。不过,我想能够做到这一点的模板只需在通过X
一次。什么我需要在为了做到这一点是:
Where X
is either, vec
, stat
, or dyn
. But I'd like to be able to do this in a template just by passing in X
again. What I'd need in order to do this is:
- 被包容的类型
- 容器大小</ li>
- The contained type
- The container size
我可以在一个功能,如:
Can I get that in a function like:
template <typename T>
void init(T& X);
还是我无法提取从尺寸信息的unique_ptr
?或者在通用时尚型? (我在的希望打上这个问题,C ++ 17的 尺寸
< /一>可以被使用。)
Or am I unable to extract size information from the unique_ptr
? Or type in a universal fashion? (I've marked this question C++17 in the hopes that size
can be used.)
推荐答案
您不会能够从独特的指针获得的大小。当您使用自动DYN = make_unique&LT; INT []&GT;(3);
它被翻译成
You are not going to be able to get the size from the unique pointer. When you use auto dyn = make_unique<int[]>(3);
it gets translated to
make_unique<int[]>(new int[3]())
这是一个指针,我们失去了大小信息。所有阵列超载确实为唯一指针更改破坏的
。如果你想使用删除
调用删除[] 的unique_ptr
阵列,那么你西港岛线需要传递的大小。
Which is a pointer and we lose the size information. All the array overload does for unique pointer is change the delete
call in the destruction to delete[]
. If you want to use an unique_ptr
"array" then you wil need to pass the size.
这篇关于用的unique_ptr&LT工作; INT []&gt;中矢量&lt; INT&gt;和INT []在模板化功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!