c++ - Correctly forward to specializations for dynamically allocated arrays -
i learned can specialize dynamically allocated arrays t[] :
template<typename t> class c {}; template<typename t> class c<t[]> {}; now while trying use such machinery, seem have trouble composing feature (using in inner layer, eg inside function template) :
#include <iostream> template<class _ty> struct op { void operator()(_ty *_ptr) const noexcept { std::cout << "single pointer\n"; delete _ptr; } }; template<class _ty> struct op<_ty[]> { void operator()(_ty *_ptr) const noexcept { std::cout << "dynamically allocated array\n"; delete[] _ptr; } }; template<typename t> void f1(t *arg) { op<t>()(arg); } int main() { f1(new int(3)); f1(new int[(3)]); } the above prints
single pointer
single pointer
when it's clear second call done array. how can fix this, doing wrong ?
both calls of same type. can verify simple program:
int main() { static_assert(std::is_same< decltype(new int(3)), decltype(new int[(3)]) >{}, "wat"); } that noted in standard in [expr.new]:
when allocated object array (that is, noptr-new-declarator syntax used or new-type-id or type-id denotes array type), new-expression yields pointer initial element (if any) of array. [ note: both
new int,new int[10]have typeint*, type ofnew int[i][10]int (*)[10]—end note ] attribute-specifier-seq in noptr-new-declarator appertains associated array type.
so there no way distinguish pointer single element pointer array by type. pass in additional tag though, like:
struct array_tag { }; struct single_tag { }; f1(new int(3), single_tag{}); f1(new int[3], array_tag{}); or explicitly specify types (this require changing couple other signatures - f1 have take t, not t*, etc):
f1(new int(3)); f1<int*>(new int(3)); f1<int[]>(new int[3]);
Comments
Post a Comment