2

为了支持数组类型作为模板参数,如何在 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++ 中显式调用固定大小数组的析构函数,那么如何执行此操作?

4

1 回答 1

2

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

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]);
}

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

于 2014-07-11T09:33:22.130 回答