c++ - 如何在C++模板中调用静态数组的析构函数?

标签 c++ templates c++11 g++ g++-4.7

如何在 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++ 中显式调用固定大小数组的析构函数,如果是,那么如何执行此操作?

最佳答案

只需对数组更加明确一点,不要忘记通过引用传递它们以避免数组衰减:

template<typename T>
void destroy(T &o) { o.~T(); }

template<typename T, size_t N>
void destroy(T (&o)[N]) {
    for(size_t i = N; i-- > 0;)
        destroy(o[i]);
}

顺便说一句:仅类型名称支持调用 dtor。 int 不是类型名称。所以,这并不困难,因为谁会想要显式地破坏显式的基本类型呢?

关于c++ - 如何在C++模板中调用静态数组的析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24694469/

相关文章:

c++ - 为什么代码不能打印这个二维数组的元素?

c++ - QT : Passing QString to QThread

c++ - 浮点值变化。不知道为什么

javascript - 创建模板并在 JS 中使用变量进行替换

c++ - g++ -Waddress 可能会误解我的意思

c++ - 是否值得添加一个支持 move 的二传手?

c++ - 英特尔 C++ 编译器 : What is highest GCC version compatibility?

c++ - 从图像数组创建单个图像

c++ - 如何修复 "Expected Primary-expression before ' )' token"错误?

php - 如何在PHP Plates模板引擎上显示错误