为了支持数组类型作为模板参数,如何在 C++11 中实现以下模板函数?当前编译失败,错误如下。是否有一些句法技巧可以解决这个问题?
template<typename T>
void destroy(T &o) { o.~T(); }
int main()
{
int x;
char y[3];
destroy(x);
destroy(y);
}
输出:
$ g++ test.cpp
test.cpp: In instantiation of ‘void destroy(T&) [with T = char [3]]’:
test.cpp:9:18: required from here
test.cpp:2:26: error: request for member ‘~char [3]’ in ‘o’, which is of non-class type ‘char [3]’
更新:如果像 struct Storage { CharType value; 这样的包装器缓冲区 } 用于代替 CharType(即 Storage* 代替 CharType*),那么这可以允许通过 Storage::~Storage() 调用 CharType = 数组的析构函数。这可以在导致这个问题的代码中起作用。但是,问题仍然存在:如果允许在 C++ 中显式调用固定大小数组的析构函数,那么如何执行此操作?